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)

    1. @Configuration
    2. @EnableWebSecurity
    3. @RestController
    4. @EnableGlobalMethodSecurity(securedEnabled = true)
    5. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    6.  
    7. @Bean(name="authenticationManager")
    8. @Override
    9. public AuthenticationManager authenticationManagerBean() throws Exception {
    10. return super.authenticationManagerBean();
    11. }
    12.  
    13. @Bean
    14. public Md5PasswordEncoder passwordEncoder() throws Exception {
    15. return new Md5PasswordEncoder();
    16. }
    17. }

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

    1. @Autowired
    2. @Qualifier("authenticationManager")
    3. protected AuthenticationManager authenticationManager;

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

    1. String username = signUp.getEmail();
    2. String password = signUp.getPassword();
    3. UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    4. request.getSession();
    5. token.setDetails(new WebAuthenticationDetails(request));
    6. Authentication authenticatedUser = authenticationManager.authenticate(token);// authenticates the token
    7.  
    8. SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
    9. request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());// creates context for that session.
    10.  
    11. //set necessary details in session
    12.  
    13. session.setAttribute("username", username);
    14. session.setAttribute("authorities", token.getAuthorities());
    15.  
    16. // after fetching the data from DB we can save important data in session like email, userId etc.
    17. 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
Reset Password
Fill out the form below and reset your password: