List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken setDetails
public void setDetails(Object details)
From source file:no.dusken.aranea.service.LoginDetailsServiceImpl.java
/** * Modify the current user's password. This should change the user's password in * the persistent user repository (datbase, LDAP etc) and should also modify the * current security context to contain the new password. * * @param oldPassword current password (for re-authentication if required) * @param newPassword the password to change to *//*from www. ja va 2 s . c o m*/ public void changePassword(String oldPassword, String newPassword) { Authentication currentUser = SecurityContextHolder.getContext().getAuthentication(); if (currentUser == null) { // This would indicate bad coding somewhere throw new AccessDeniedException( "Can't change password as no Authentication object found in context " + "for current user."); } String username = currentUser.getName(); LoginDetails user = (LoginDetails) loadUserByUsername(username); // If an authentication manager has been set, reauthenticate the user with the supplied password. if (authenticationManager != null) { logger.info("Reauthenticating user '{}' for password change request.", username); authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword)); } else { logger.debug("No authentication manager set. Password won't be re-checked."); } logger.info("Changing password for user '{}'", username); String encoded = encoder.encodePassword(newPassword, username); user.setPassword(encoded); super.saveOrUpdate(user); //reauthenticating with the new password. UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()); newAuthentication.setDetails(currentUser.getDetails()); SecurityContextHolder.getContext().setAuthentication(newAuthentication); }
From source file:ru.org.linux.auth.LoginController.java
@RequestMapping(value = "/ajax_login_process", method = RequestMethod.POST) @ResponseBody//from w w w. j a v a 2 s . co m public LoginStatus loginAjax(@RequestParam("nick") final String username, @RequestParam("passwd") final String password, HttpServletRequest request, HttpServletResponse response) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); try { UserDetailsImpl details = (UserDetailsImpl) userDetailsService.loadUserByUsername(username); token.setDetails(details); Authentication auth = authenticationManager.authenticate(token); UserDetailsImpl userDetails = (UserDetailsImpl) auth.getDetails(); if (!userDetails.getUser().isActivated()) { return new LoginStatus(false, "User not activated"); } SecurityContextHolder.getContext().setAuthentication(auth); rememberMeServices.loginSuccess(request, response, auth); AuthUtil.updateLastLogin(auth, userDao); return new LoginStatus(auth.isAuthenticated(), auth.getName()); } catch (LockedException e) { return new LoginStatus(false, "User locked"); } catch (UsernameNotFoundException e) { return new LoginStatus(false, "Bad credentials"); } catch (BadCredentialsException e) { return new LoginStatus(false, e.getMessage()); } }
From source file:alpha.portal.webapp.controller.SignupController.java
/** * On submit./*from w ww . j a v a 2 s. c om*/ * * @param user * the user * @param errors * the errors * @param request * the request * @param response * the response * @return the string * @throws Exception * the exception */ @RequestMapping(method = RequestMethod.POST) public String onSubmit(final User user, final BindingResult errors, final HttpServletRequest request, final HttpServletResponse response) throws Exception { if (request.getParameter("cancel") != null) return this.getCancelView(); if (this.log.isDebugEnabled()) { this.log.debug("entering 'onSubmit' method..."); } final Locale locale = request.getLocale(); user.setEnabled(true); // Set the default user role on this new user user.addRole(this.roleManager.getRole(Constants.USER_ROLE)); try { this.getUserManager().saveUser(user); } catch (final AccessDeniedException ade) { // thrown by UserSecurityAdvice configured in aop:advisor // userManagerSecurity this.log.warn(ade.getMessage()); response.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } catch (final UserExistsException e) { errors.rejectValue("username", "errors.existing.user", new Object[] { user.getUsername(), user.getEmail() }, "duplicate user"); // redisplay the unencrypted passwords user.setPassword(user.getConfirmPassword()); return "signup"; } this.saveMessage(request, this.getText("user.registered", user.getUsername(), locale)); request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE); // log user in automatically final UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getConfirmPassword(), user.getAuthorities()); auth.setDetails(user); SecurityContextHolder.getContext().setAuthentication(auth); // Send user an e-mail if (this.log.isDebugEnabled()) { this.log.debug("Sending user '" + user.getUsername() + "' an account information e-mail"); } // Send an account information e-mail this.message.setSubject(this.getText("signup.email.subject", locale)); try { this.sendUserMessage(user, this.getText("signup.email.message", locale), RequestUtil.getAppURL(request)); } catch (final MailException me) { this.saveError(request, me.getMostSpecificCause().getMessage()); } return this.getSuccessView(); }
From source file:net.navasoft.madcoin.backend.services.rest.impl.TokenVerifierFilter.java
/** * Do filter.//www . j ava 2s. c om * * @param request * the request * @param response * the response * @param chain * the chain * @throws IOException * Signals that an I/O exception has occurred. * @throws ServletException * the servlet exception * @since 8/09/2014, 10:28:12 AM */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Map<String, String[]> parms = request.getParameterMap(); if (parms.containsKey("allowanceToken")) { String token = parms.get("allowanceToken")[0]; try { if (tokenUtils.validate(token)) { UserDetails userDetails = tokenUtils.getUserFromToken(token); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), userDetails.getPassword()); authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request)); SecurityContextHolder.getContext().setAuthentication(userManager.authenticate(authentication)); } } catch (BadPaddingException e) { } catch (AuthenticationException e) { } } else if (parms.containsKey("workerToken")) { String token = parms.get("workerToken")[0]; try { if (providerTokenUtils.validate(token)) { UserDetails userDetails = providerTokenUtils.getUserFromToken(token); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), userDetails.getPassword()); authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request)); SecurityContextHolder.getContext() .setAuthentication(providerManager.authenticate(authentication)); } } catch (BadPaddingException e) { e.printStackTrace(); } catch (AuthenticationException e) { e.printStackTrace(); } } chain.doFilter(request, response); }
From source file:org.openmrs.contrib.metadatarepository.service.impl.UserSecurityAdviceTest.java
@Before public void setUp() throws Exception { // store initial security context for later restoration initialSecurityContext = SecurityContextHolder.getContext(); SecurityContext context = new SecurityContextImpl(); User user = new User("user"); user.setId(1L);/*from w w w . j a v a2s . c o m*/ user.setPassword("password"); user.addRole(new Role(Constants.USER_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities()); token.setDetails(user); context.setAuthentication(token); SecurityContextHolder.setContext(context); }
From source file:org.trustedanalytics.servicecatalog.security.JwtUserDetailsTokenConverter.java
@Override public Authentication extractAuthentication(Map<String, ?> map) { if (!map.containsKey(USERNAME)) { return null; }/* w w w . j ava 2 s .co m*/ if (map.containsKey(AUTHORITIES)) { return super.extractAuthentication(map); } if (map.containsKey(SCOPE)) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(map.get(USERNAME), "N/A", getAuthorities(map)); if (map.containsKey(USER_ID)) { AccessTokenDetails details = new AccessTokenDetails(UUID.fromString((String) map.get(USER_ID))); token.setDetails(details); } return token; } return null; }
From source file:org.openmrs.contrib.metadatarepository.service.impl.UserSecurityAdviceTest.java
@Test public void testAddUserAsAdmin() throws Exception { SecurityContext securityContext = new SecurityContextImpl(); User user = new User("admin"); user.setId(2L);//from w ww . ja v a2 s . c o m user.setPassword("password"); user.addRole(new Role(Constants.ADMIN_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities()); token.setDetails(user); securityContext.setAuthentication(token); SecurityContextHolder.setContext(securityContext); UserManager userManager = makeInterceptedTarget(); final User adminUser = new User("admin"); adminUser.setId(2L); context.checking(new Expectations() { { one(userDao).saveUser(with(same(adminUser))); } }); userManager.saveUser(adminUser); }
From source file:org.openmrs.contrib.metadatarepository.service.impl.UserSecurityAdviceTest.java
@Test public void testAddUserRoleWhenHasAdminRole() throws Exception { SecurityContext securityContext = new SecurityContextImpl(); User user1 = new User("user"); user1.setId(1L);/*from w ww .jav a2 s. c om*/ user1.setPassword("password"); user1.addRole(new Role(Constants.ADMIN_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user1.getUsername(), user1.getPassword(), user1.getAuthorities()); token.setDetails(user1); securityContext.setAuthentication(token); SecurityContextHolder.setContext(securityContext); UserManager userManager = makeInterceptedTarget(); final User user = new User("user"); user.setId(1L); user.getRoles().add(new Role(Constants.ADMIN_ROLE)); user.getRoles().add(new Role(Constants.USER_ROLE)); context.checking(new Expectations() { { one(userDao).saveUser(with(same(user))); } }); userManager.saveUser(user); }
From source file:org.appverse.web.framework.backend.security.authentication.userpassword.filters.CustomUserNamePasswordAuthenticationFilter.java
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { final boolean debug = logger.isDebugEnabled(); String uri = request.getRequestURI().substring(request.getContextPath().length()); if (userNamePasswordAuthenticationUri == null || !uri.equals(userNamePasswordAuthenticationUri)) { chain.doFilter(request, response); return;/*from w ww.j a va 2s. c om*/ } try { String[] tokens = extractUserNameAndPassword(request); assert tokens.length == 2; String username = tokens[0]; if (debug) { logger.debug("Username and password attributes found for user '" + username + "'"); } if (authenticationIsRequired(username)) { UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, tokens[1]); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); Authentication authResult = authenticationManager.authenticate(authRequest); if (debug) { logger.debug("Authentication success: " + authResult); } SecurityContextHolder.getContext().setAuthentication(authResult); rememberMeServices.loginSuccess(request, response, authResult); onSuccessfulAuthentication(request, response, authResult); } } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request for failed: " + failed); } rememberMeServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, failed); if (ignoreFailure) { chain.doFilter(request, response); } else { authenticationEntryPoint.commence(request, response, failed); } return; } chain.doFilter(request, response); }
From source file:com.sun.identity.provider.springsecurity.OpenSSOProcessingFilter.java
protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) { Object o = authenticationDetailsSource.buildDetails(request); // if (debug.messageEnabled()) { // debug.message("Details object= " + o.getClass() + " val=" + o); // }/* w ww . j a v a 2 s .co m*/ authRequest.setDetails(o); }