Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Spring Security 4: Auto login with annotation

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.46k
    Comment on it

    Spring security gives us the feature to auto login into the system just after creating an account. Other way is to register then go to login page, and then login to the system. When we login login mechanism spring automatically creates the session for it while if we do auto login we have to do it by some code. Here is the sample code for auto login:

    Define a bean in WebSecurityConfigurerAdapter and give bean a name(authenticationManager)

    @EnableGlobalMethodSecurity(securedEnabled = true)
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        public Md5PasswordEncoder passwordEncoder() throws Exception {
          return new Md5PasswordEncoder();

    Here our password in md5 encrypted. Now will will use this bean in our controller as:

    protected AuthenticationManager authenticationManager;

    Here is bean is referenced via the Qualifier name. Now the code for auto login is somewhat like:

    String username = signUp.getEmail();
    String password = signUp.getPassword();
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    token.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticatedUser = authenticationManager.authenticate(token);// authenticates the token
                request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());// creates context for that session.
    //set necessary details in session
    session.setAttribute("username", username);
    session.setAttribute("authorities", token.getAuthorities());
    // after fetching the data from DB we can save important data in session like email, userId etc.
    User user = userService.findByUserName(username);

    Now we can proceed to our normal procedure.

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: