Spring Security Auto Login After Successful Registration

Asking your user to login immediately after he/she registers might be tedious. Here’s how you can log them in immediately using Spring Security (thanks to this SO thread).

Typically you will have some sort of registration form with a backing controller like this:


("/register")
public class RegisterController {
  ...
  (method = POST)
  public String register( User user) {
    // perform registration logic..
    // redirect back to login page
    return "redirect:/login";
  }
  ...
}

But a server-side login can be done by autowiring UserDetailService and AuthenticationManager:


("/register")
public class RegisterController {
  ...
   ("authMgr") private AuthenticationManager authMgr;
   private UserDetailsService userDetailsSvc;

  (method = POST)
  public String register( User user) {
    // perform registration logic..

    // perform login authentication
    try {
      UserDetails userDetails = userDetailsSvc.loadUserByUsername(username);
      UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
      authMgr.authenticate(auth);

      // redirect into secured main page if authentication successful
      if(auth.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(auth);
        return "redirect:/";
      }
    } catch (Exception e) {
      logger.debug("Problem authenticating user" + username, e);
    }

    return "redirect:/error";
  }
  ...
}

Note that in above code the AuthenticationManager injection is qualified by ("authMgr"). This is to avoid multiple beans ambiguity. In effect in the xml context configuration (if you use one) an id attribute has to be set:

  ...
  
    ...
  

  
    ...
  
  ...

Also in order for this setup to work, the registration page has to be filtered by spring security

  ...
  
  

  
    
  
  ...

See Also

Installing Spring Security On Spring MVC Project

Leave a Reply