List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken
public UsernamePasswordAuthenticationToken(Object principal, Object credentials)
UsernamePasswordAuthenticationToken
, as the #isAuthenticated() will return false
. From source file:com.create.security.oauth2.provider.token.SpringCacheTokenStoreImplTest.java
private OAuth2Authentication createOAuth2Authentication() { final OAuth2Request storedRequest = new OAuth2Request(Collections.emptyMap(), CLIENT_ID, Collections.<GrantedAuthority>emptyList(), true, Collections.<String>emptySet(), Collections.<String>emptySet(), null, Collections.<String>emptySet(), Collections.<String, Serializable>emptyMap()); final User userDetails = new User(USER_NAME, PASSWORD, Collections.EMPTY_SET); final Authentication userAuthentication = new UsernamePasswordAuthenticationToken(userDetails, null); return new OAuth2Authentication(storedRequest, userAuthentication); }
From source file:org.sharetask.controller.UserController.java
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public void performLogin(@RequestBody final UserPassword login, final HttpServletRequest request, final HttpServletResponse response) { final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( login.getUsername(), login.getPassword()); try {//from ww w . j a v a 2 s .c o m final Authentication auth = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(auth); repository.saveContext(SecurityContextHolder.getContext(), request, response); rememberMeServices.loginSuccess(request, response, auth); // language cookie final UserInfoDTO user = userService.read(SecurityUtil.getCurrentSignedInUsername()); final Cookie locale = new Cookie(RequestUltil.LOCALE, user.getLanguage()); locale.setMaxAge(-1); locale.setPath("/"); response.addCookie(locale); response.setStatus(HttpStatus.OK.value()); } catch (final BadCredentialsException ex) { response.setStatus(HttpStatus.UNAUTHORIZED.value()); } }
From source file:org.vaadin.spring.security.AbstractVaadinSecurity.java
@Override public Authentication login(String username, String password) throws AuthenticationException, Exception { return login(new UsernamePasswordAuthenticationToken(username, password)); }
From source file:org.appverse.web.framework.backend.security.authentication.userpassword.managers.UserAndPasswordAuthenticationManagerImpl.java
/** * Takes the username and password as provided and checks the validaty of * the credentials. Spring security is used to check the credentielas and to * return the authenticated principal with it's authorized roles. An * exception is thrown if the authentication failes. * /*ww w . ja v a2 s . com*/ * @param username * String containing the username of the principal to login * @param password * String containing the password used to identify the current * user * @return AuthorizationData object containing the name of the principal * and the authorized roles. */ @SuppressWarnings("unchecked") @Override public AuthorizationData authenticatePrincipal(final String username, final String password) { final UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( username, password); final Authentication authentication = authenticationManager .authenticate(usernamePasswordAuthenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); final Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) SecurityContextHolder .getContext().getAuthentication().getAuthorities(); final List<String> grantedRoles = new ArrayList<String>(); for (final GrantedAuthority grantedAuthority : authorities) { grantedRoles.add(grantedAuthority.getAuthority()); } final String name = SecurityContextHolder.getContext().getAuthentication().getName(); return new AuthorizationData(grantedRoles, name); }
From source file:ch.ge.ve.protopoc.controller.impl.AuthenticationController.java
@Override public ResponseEntity<?> createAuthenticationToken( @RequestBody JwtAuthenticationRequest authenticationRequest) { logger.info(String.format("Attempting login for user [%s]", authenticationRequest.getUsername())); // Perform the security final Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-security so we can generate token final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); final String token = jwtTokenUtil.generateToken(userDetails); // Return the token return ResponseEntity.ok(new JwtAuthenticationResponse(token)); }
From source file:hsa.awp.event.facade.TestEventFacadeSecurity.java
@Before public void setUp() { securityContext = SecurityContextHolder.getContext(); secretaryAuthentication = new UsernamePasswordAuthenticationToken("secretary", "password"); adminAuthentication = new UsernamePasswordAuthenticationToken("admin", "password"); facultyAuthentication = new UsernamePasswordAuthenticationToken("faculty", "password"); studentAuthentication = new UsernamePasswordAuthenticationToken("student", "password"); securityContext.setAuthentication(null); mockery = mockFactory.getMockery();/* www . j a v a 2 s . c o m*/ categoryDao = mockFactory.getCategoryDao(); eventDao = mockFactory.getEventDao(); subjectDao = mockFactory.getSubjectDao(); termDao = mockFactory.getTermDao(); mockery.checking(new Expectations() { { allowing(categoryDao).findAll(); will(returnValue(new ArrayList<Category>())); allowing(categoryDao).remove(Category.getInstance("", 0L)); allowing(categoryDao); will(returnValue(Category.getInstance("", 0L))); allowing(eventDao).findAll(); will(returnValue(new ArrayList<Event>())); allowing(eventDao).remove(Event.getInstance(0, 0L)); allowing(eventDao); will(returnValue(Event.getInstance(0, 0L))); allowing(subjectDao).findAll(); will(returnValue(new ArrayList<Subject>())); allowing(subjectDao).remove(Subject.getInstance(0L)); allowing(subjectDao); will(returnValue(Subject.getInstance(0L))); allowing(termDao).findAll(); will(returnValue(new ArrayList<Term>())); allowing(subjectDao).remove(Subject.getInstance(0L)); allowing(termDao); will(returnValue(Term.getInstance(0L))); } }); }
From source file:org.appverse.web.framework.backend.api.services.presentation.impl.live.AuthenticationServiceFacadeImpl.java
/** * Takes the username and password as provided and checks the validaty of * the credentials. Spring security is used to check the credentielas and to * return the authenticated principal with it's authorized roles. An * exception is thrown if the authentication failes. * /*from w ww .j ava 2 s .c om*/ * @param username * String containing the username of the principal to login * @param password * String containing the password used to identify the current * user * @return AuthorizationDataVO object containing the name of the principal * and the authorized roles. */ @SuppressWarnings("unchecked") @Override public AuthorizationDataVO authenticatePrincipal(final String username, final String password) { final UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( username, password); final Authentication authentication = authenticationManager .authenticate(usernamePasswordAuthenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); final Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) SecurityContextHolder .getContext().getAuthentication().getAuthorities(); final List<String> grantedRoles = new ArrayList<String>(); for (final GrantedAuthority grantedAuthority : authorities) { grantedRoles.add(grantedAuthority.getAuthority()); } final String name = SecurityContextHolder.getContext().getAuthentication().getName(); return new AuthorizationDataVO(grantedRoles, name); }
From source file:org.apache.coheigea.cxf.spring.security.authentication.SpringSecurityUTValidator.java
public Credential validate(Credential credential, RequestData data) throws WSSecurityException { if (credential == null || credential.getUsernametoken() == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential"); }/*w w w .j a v a 2s. c om*/ // Validate the UsernameToken UsernameToken usernameToken = credential.getUsernametoken(); String pwType = usernameToken.getPasswordType(); if (log.isDebugEnabled()) { log.debug("UsernameToken user " + usernameToken.getName()); log.debug("UsernameToken password type " + pwType); } if (!WSConstants.PASSWORD_TEXT.equals(pwType)) { if (log.isDebugEnabled()) { log.debug("Authentication failed - digest passwords are not accepted"); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } if (usernameToken.getPassword() == null) { if (log.isDebugEnabled()) { log.debug("Authentication failed - no password was provided"); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } // Validate it via Spring Security // Set a Subject up UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( usernameToken.getName(), usernameToken.getPassword()); Subject subject = new Subject(); subject.getPrincipals().add(authToken); Set<Authentication> authentications = subject.getPrincipals(Authentication.class); Authentication authenticated = null; try { authenticated = authenticationManager.authenticate(authentications.iterator().next()); } catch (AuthenticationException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } if (!authenticated.isAuthenticated()) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } for (GrantedAuthority authz : authenticated.getAuthorities()) { System.out.println("Granted: " + authz.getAuthority()); } // Authorize request if (accessDecisionManager != null && !requiredRoles.isEmpty()) { List<ConfigAttribute> attributes = SecurityConfig .createList(requiredRoles.toArray(new String[requiredRoles.size()])); for (ConfigAttribute attr : attributes) { System.out.println("Attr: " + attr.getAttribute()); } accessDecisionManager.decide(authenticated, this, attributes); } credential.setSubject(subject); return credential; }
From source file:com.auditbucket.test.functional.TestTxReference.java
@Test public void testAuthorisedToViewTransaction() throws Exception { SystemUser suABC = regService.registerSystemUser(new RegistrationBean("ABC", "mike@monowai.com", "bah")); SystemUser suCBA = regService.registerSystemUser(new RegistrationBean("CBA", "null@monowai.com", "bah")); Authentication authABC = new UsernamePasswordAuthenticationToken(suABC.getName(), "user1"); Authentication authCBA = new UsernamePasswordAuthenticationToken(suCBA.getName(), "user1"); // ABC Data/* www. ja v a 2 s . c om*/ Fortress fortressABC = fortressService.registerFortress("abcTest"); MetaInputBean abcHeader = new MetaInputBean(fortressABC.getName(), "wally", "TestTrack", new DateTime(), "ABC123"); abcHeader.setLog(new LogInputBean(null, "charlie", DateTime.now(), escJsonA, true)); TrackResultBean resultBean = auditManager.createHeader(abcHeader, null); LogResultBean logResultBean = resultBean.getLogResult(); assertNotNull(logResultBean); String abcTxRef = logResultBean.getTxReference(); assertNotNull(abcTxRef); // CBA data SecurityContextHolder.getContext().setAuthentication(authCBA); Fortress fortressCBA = fortressService.registerFortress("cbaTest"); MetaInputBean cbaHeader = new MetaInputBean(fortressCBA.getName(), "wally", "TestTrack", new DateTime(), "ABC123"); String cbaKey = auditManager.createHeader(cbaHeader, null).getMetaKey(); LogInputBean cbaLog = new LogInputBean(cbaKey, "charlie", DateTime.now(), escJsonA, true); assertEquals("CBA Logger Not Created", LogInputBean.LogStatus.OK, auditManager.processLog(cbaLog).getStatus()); String cbaTxRef = cbaLog.getTxRef(); assertNotNull(cbaTxRef); // CBA Caller can not see the ABC transaction assertNotNull(trackService.findTx(cbaTxRef)); assertNull(trackService.findTx(abcTxRef)); // ABC Caller cannot see the CBA transaction SecurityContextHolder.getContext().setAuthentication(authABC); assertNotNull(trackService.findTx(abcTxRef)); assertNull(trackService.findTx(cbaTxRef)); // WHat happens if ABC tries to use CBA's TX Ref. abcHeader = new MetaInputBean(fortressABC.getName(), "wally", "TestTrack", new DateTime(), "ZZZAAA"); abcHeader.setLog(new LogInputBean(null, "wally", DateTime.now(), escJsonA, null, cbaTxRef)); TrackResultBean result = auditManager.createHeader(abcHeader, null); assertNotNull(result); // It works because TX References have only to be unique for a company // ab generated references are GUIDs, but the caller is allowed to define their own transaction assertNotNull(trackService.findTx(cbaTxRef)); }