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.49k
    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)

    @Configuration
    @EnableWebSecurity
    @RestController
    @EnableGlobalMethodSecurity(securedEnabled = true)
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Bean(name="authenticationManager")
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
    
        @Bean
        public Md5PasswordEncoder passwordEncoder() throws Exception {
          return new Md5PasswordEncoder();
        }
    }
    

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

    @Autowired 
    @Qualifier("authenticationManager")
    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);
    request.getSession();
    token.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticatedUser = authenticationManager.authenticate(token);// authenticates the token
    
    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
                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
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
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: