Auto login after successful registration

Viewed 30944

hey all i want to make an auto login after successful registration in spring meaning: i have a protected page which requires login to access them and i want after registration to skip the login page and make an auto login so the user can see that protected page, got me ? i am using spring 3.0 , spring security 3.0.2 how to do so ?

10 Answers

I incorporated the same scenario, below is the code snippet. To get the instance of AuthenticationManager, you will need to override the authenticationManagerBean() method of WebSecurityConfigurerAdapter class

SecurityConfiguration(extends WebSecurityConfigurerAdapter)

@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

Controller

    @Autowired
    protected AuthenticationManager authenticationManager;

    @PostMapping("/register")
    public ModelAndView registerNewUser(@Valid User user,BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        User userObj = userService.findUserByEmail(user.getEmail());
        if(userObj != null){
            bindingResult.rejectValue("email", "error.user", "This email id is already registered.");
        }
        if(bindingResult.hasErrors()){
            modelAndView.setViewName("register");
            return modelAndView;
        }else{
            String unEncodedPwd = user.getPassword();
            userService.saveUser(user);
            modelAndView.setViewName("view_name");
            authWithAuthManager(request,user.getEmail(),unEncodedPwd);
        }   
        return modelAndView;
    }


    public void authWithAuthManager(HttpServletRequest request, String email, String password) {
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(email, password);
        authToken.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = authenticationManager.authenticate(authToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
Related