List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken
public UsernamePasswordAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities)
AuthenticationManager
or AuthenticationProvider
implementations that are satisfied with producing a trusted (i.e. From source file:com.px100systems.data.browser.controller.MainController.java
public void autoLogin(HttpServletRequest request, String username, String password) { List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(); authorities.add(new SimpleGrantedAuthority(DbBrowserUserDetailsService.DEFAULT_AUTHORITY)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password, authorities);/*from ww w. j ava 2 s . c om*/ request.getSession(); token.setDetails(new WebAuthenticationDetails(request)); Authentication authenticatedUser = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authenticatedUser); HttpSession session = request.getSession(); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); session.setAttribute(USER_ATTRIBUTE, username); }
From source file:org.dspace.EDMExport.service.EDMExportAuthenticationManager.java
/** * Redefinimos el mtodo para autenticarse * /* ww w . j a v a2 s .co m*/ * @param auth objeto de Spring de Authentication {@link Authentication} * @return UsernamePasswordAuthenticationToken {@link Authentication} * @throws AuthenticationException */ @Override public Authentication authenticate(Authentication auth) throws AuthenticationException { logger.debug("Performing EDMExport authentication"); try { // Buscar usuario con login y grupo o slo con login if (groupIDStr != null && !groupIDStr.isEmpty()) { eperson = daoEperson.getEperson(auth.getName(), Integer.parseInt(groupIDStr)); } else eperson = daoEperson.getEperson(auth.getName()); } catch (Exception e) { logger.error("User " + auth.getName() + " does not exists! " + e.getMessage() + "," + e.toString(), e); //SecurityContextHolder.getContext().setAuthentication(null); throw new BadCredentialsException("User does not exists!"); } // Validamos el password if (!passwordEncoder.isPasswordValid(eperson.getPassword(), (String) auth.getCredentials(), null)) { logger.error("Wrong password!" + eperson.getPassword() + " " + (String) auth.getCredentials()); throw new BadCredentialsException("Wrong password!"); } // Comprobamos que el login no se igual que el password, poco seguridad if (auth.getName().equals(auth.getCredentials())) { logger.debug("Entered username and password are the same!"); throw new BadCredentialsException("Entered username and password are the same!"); } else { logger.debug("User details are good and ready to go"); return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), getAuthorities(eperson.getAccess())); } }
From source file:org.openengsb.opencit.ui.web.AbstractCitPageTest.java
private void mockAuthentication() { AuthenticationManager authManager = mock(AuthenticationManager.class); final Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new GrantedAuthorityImpl("ROLE_USER")); when(authManager.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() { @Override//from w w w .j a va 2 s . c o m public Authentication answer(InvocationOnMock invocation) { Authentication auth = (Authentication) invocation.getArguments()[0]; if (auth.getCredentials().equals("password")) { return new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), authorities); } throw new BadCredentialsException("wrong password"); } }); appContext.putBean("authenticationManager", authManager); }
From source file:de.iew.framework.security.access.WebResourceAccessEvaluatorTest.java
private Authentication newUserAuthenticationToken() { List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER")); return new UsernamePasswordAuthenticationToken("JUnit", "JUnit", grantedAuthorities); }
From source file:com.ai.bss.webui.security.AiBssAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; }//w w w .ja v a 2 s.co m UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String username = token.getName(); String password = String.valueOf(token.getCredentials()); FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>(); AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray()); try { // commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback); // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before // the command is dispatched. } catch (StructuralCommandValidationFailedException e) { e.printStackTrace(); return null; } UserAccount account; try { account = accountCallback.get(); if (account == null) { throw new BadCredentialsException("Invalid username and/or password"); } } catch (InterruptedException e) { throw new AuthenticationServiceException("Credentials could not be verified", e); } catch (ExecutionException e) { throw new AuthenticationServiceException("Credentials could not be verified", e); } UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account, authentication.getCredentials(), userAuthorities); result.setDetails(authentication.getDetails()); return result; }
From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = (String) authentication.getCredentials(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(); parameters.set("username", username); parameters.set("password", password); @SuppressWarnings("rawtypes") ResponseEntity<Map> response = restTemplate.exchange(loginUrl, HttpMethod.POST, new HttpEntity<MultiValueMap<String, Object>>(parameters, headers), Map.class); if (response.getStatusCode() == HttpStatus.OK) { String userFromUaa = (String) response.getBody().get("username"); if (userFromUaa.equals(userFromUaa)) { logger.info("Successful authentication request for " + authentication.getName()); return new UsernamePasswordAuthenticationToken(username, null, UaaAuthority.USER_AUTHORITIES); }/*from w w w . j a va 2 s . com*/ } else if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) { logger.info("Failed authentication request"); throw new BadCredentialsException("Authentication failed"); } else if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) { logger.info("Internal error from UAA. Please Check the UAA logs."); } else { logger.error("Unexpected status code " + response.getStatusCode() + " from the UAA." + " Is a compatible version running?"); } throw new RuntimeException("Could not authenticate with remote server"); }
From source file:org.axonframework.samples.trader.webui.security.TraderAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; }//from w w w . jav a 2 s . c om UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String username = token.getName(); String password = String.valueOf(token.getCredentials()); FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>(); AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray()); try { commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback); // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before // the command is dispatched. } catch (StructuralCommandValidationFailedException e) { return null; } UserAccount account; try { account = accountCallback.get(); if (account == null) { throw new BadCredentialsException("Invalid username and/or password"); } } catch (InterruptedException e) { throw new AuthenticationServiceException("Credentials could not be verified", e); } catch (ExecutionException e) { throw new AuthenticationServiceException("Credentials could not be verified", e); } UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account, authentication.getCredentials(), userAuthorities); result.setDetails(authentication.getDetails()); return result; }
From source file:uk.org.rbc1b.roms.controller.volunteer.contactdetails.VolunteerContactDetailsConfirmationController.java
/** * Show the volunteer contact details confirmed page when a volunteer * accesses this URI endpoint.//from w ww .j a va2 s.co m * * @param volunteerId the volunteer * @param dateTime date time for the expiration of this URI * @param hash the hash * @return String view */ @RequestMapping(value = "/{volunteerId}/{dateTime}/{hash}", method = RequestMethod.GET) public String showContactDetailsConfirmation(@PathVariable Integer volunteerId, @PathVariable String dateTime, @PathVariable String hash) { Volunteer volunteer = volunteerDao.findVolunteer(volunteerId, VOLUNTEER_DATA); if (volunteer == null) { return "volunteers/contact-details-confirmation/error"; } HashAndDateTimeValidator hashDateTimeValidator = new HashAndDateTimeValidator(); hashDateTimeValidator.setDateTimeFormat(DATETIMEFORMAT); hashDateTimeValidator.setMaxTime(MAXTIME); hashDateTimeValidator.setSalt(edificeProperty.getProperty(SECURITY_SALT)); String value = dateTime + ":" + volunteerId; if (hashDateTimeValidator.checkWithinTime(dateTime) && hashDateTimeValidator.checkHash(value, hash)) { final DateTime dt = new DateTime(); volunteer.setContactDetailsLastConfirmed(DataConverterUtil.toSqlDate(dt)); UserDetails system = userDetailsService.loadUserByUsername("System"); Authentication authentication = new UsernamePasswordAuthenticationToken(system, system.getUsername(), system.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); volunteerDao.updateVolunteer(volunteer); return "volunteers/contact-details-confirmation/view"; } return "volunteers/contact-details-confirmation/error"; }
From source file:org.cloudfoundry.identity.uaa.login.AccountsController.java
@RequestMapping(value = "/verify_user", method = GET) public String verifyUser(Model model, @RequestParam("code") String code, HttpServletResponse response) throws IOException { AccountCreationService.AccountCreationResponse accountCreation; try {/* w w w . j a v a 2 s . c o m*/ accountCreation = accountCreationService.completeActivation(code); } catch (HttpClientErrorException e) { model.addAttribute("error_message_code", "code_expired"); response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value()); return "accounts/new_activation_email"; } UaaPrincipal uaaPrincipal = new UaaPrincipal(accountCreation.getUserId(), accountCreation.getUsername(), accountCreation.getEmail(), Origin.UAA, null); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(uaaPrincipal, null, UaaAuthority.USER_AUTHORITIES); SecurityContextHolder.getContext().setAuthentication(token); String redirectLocation = accountCreation.getRedirectLocation(); if (redirectLocation == null) { redirectLocation = "home"; } return "redirect:" + redirectLocation; }