Auto login after successful registration

0 votes
asked Sep 28, 2010 by mahmoud-saleh

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 ?

9 Answers

0 votes
answered by andy
  1. Configure web.xml to allow Spring Security to handle forwards for a login processing url.
  2. Handle registration request, e.g. create user, update ACL, etc.
  3. Forward it with username and password to login processing url for authentication.
  4. Gain benefits of entire Spring Security filter chain, e.g. session fixation protection.

Since forwards are internal, it will appear to the user as if they are registered and logged in during the same request.

If your registration form does not contain the correct username and password parameter names, forward a modified version of the request (using HttpServletRequestWrapper) to the Spring Security login endpoint.

In order for this to work, you'll have to modify your web.xml to have the Spring Security filter chain handle forwards for the login-processing-url. For example:


<!-- Handle authentication for normal requests. -->

<!-- Handle authentication via forwarding for internal/automatic authentication. -->

Source: mohchi blog

0 votes
answered Jan 28, 2010 by sinuhepop

I'm not sure if you are asking for this, but in your Spring Security configuration you can add a "remember-me" tag. This will manage a cookie in your client, so next time (if the cookie hasn't expired) you'll be logged automatically.

    <remember-me />
0 votes
answered Sep 28, 2010 by spring-monkey

This can be done with spring security in the following manner(semi-psuedocode):


public class SignupController

    RequestCache requestCache;

    protected AuthenticationManager authenticationManager;

    @RequestMapping(value = "/account/signup/", method = RequestMethod.POST)
    public String createNewUser(@ModelAttribute("user") User user, BindingResult result,  HttpServletRequest request, HttpServletResponse response) {
        //After successfully Creating user
        authenticateUserAndSetSession(user, request);

        return "redirect:/home/";

    private void authenticateUserAndSetSession(User user, HttpServletRequest request) {
        String username = user.getUsername();
        String password = user.getPassword();
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

        // generate session if one doesn't exist

        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authenticatedUser = authenticationManager.authenticate(token);


Update: to only contain how to create the session after the registration

0 votes
answered Sep 14, 2011 by user844085

Just a comment to the first reply on how to autowire authenticationManager.

You need to set an alias when you declare authentication-manager in either your applicantion-servlet.xml or applicationContext-security.xml file:

<authentication-manager alias="authenticationManager>
            <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
            <user name="bob" password="bobspassword" authorities="ROLE_USER" />

Also, when you authenticate, it may throw an AuthenticationException, so you need to catch it:

UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());

token.setDetails(new WebAuthenticationDetails(request));

    Authentication auth = authenticationManager.authenticate(token);

} catch(Exception e){

return "redirect:xxxx.htm";
0 votes
answered Sep 11, 2014 by gerrytan

Spring Monkey's answer works great but I encountered a tricky problem when implementing it.

My problem was because I set the registration page to have "no security", eg:

<http pattern="/register/**" security="none"/>

I think this causes no SecurityContext initialized, and hence after user registers, the in-server authentication cannot be saved.

I had to change the register page bypass by setting it into IS_AUTHENTICATED_ANONYMOUSLY

<http authentication-manager-ref="authMgr">
  <intercept-url pattern="/register/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
0 votes
answered Sep 11, 2015 by henok-t

In Servlet 3+ you can simply do request.login("username","password") and if successful, redirect to whatever page you want. You can do the same for auto logout.

Here is the link to the section of the documentation that talks about this:

0 votes
answered Sep 15, 2017 by dillon-ryan-redding

This is an alternative to the Servlet 3+ integration. If you're using Spring Security's form login, then you can simply delegate to your login page. For example:

public String signUp(User user) {
    // encode the password and save the user
    return "forward:/login";

Assuming you have username and password fields in your form, then the 'forward' will send those parameters and Spring Security will use those to authenticate.

The benefit I found with this approach is that you don't duplicate your formLogin's defaultSuccessUrl (example security setup below). It also cleans up your controller by not requiring a HttpServletRequest parameter.

public void configure(HttpSecurity http) {
            .antMatchers("/", "/signup").permitAll()
            .defaultSuccessUrl("/home", true)
0 votes
answered Sep 15, 2017 by ankit-pandoh

Using SecurityContextHolder.getContext().setAuthentication(Authentication) gets the job done but it will bypass the spring security filter chain which will open a security risk.

For e.g. lets say in my case when user reset the password, I wanted him to take to the dashboard without login again. When I used the above said approach, it takes me to dashboard but it bypassed my concurrency filter which I have applied in order to avoid concurrent login. Here is the piece of code which does the job:

UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(empId, password);
Authentication auth = authenticationManager.authenticate(authToken);

Use login-processing-url attribute along with a simple change in web.xml


<form-login login-page="/login" 



By adding this piece of code in web.xml actually does the job of forwarding your explicit forward request which you will make during auto login and passing it to the chain of spring security filters.

Hope it helps

0 votes
answered Sep 15, 2017 by yogesh-devgun

This is answer to above question In Controller:

@RequestMapping(value = "/registerHere", method = RequestMethod.POST)
    public ModelAndView registerUser(@ModelAttribute("user") Users user, BindingResult result,
            HttpServletRequest request, HttpServletResponse response) {
        System.out.println("register 3");

        ModelAndView mv = new ModelAndView("/home");
        mv.addObject("homePagee", "true");

        String uname = user.getUsername();

        if (userDAO.getUserByName(uname) == null) {

            String passwordFromForm = user.getPassword();

            try {
                authenticateUserAndSetSession(user, passwordFromForm, request);
            } catch (Exception e) {
                // TODO Auto-generated catch block


        System.out.println("register 4");

        log.debug("Ending of the method registerUser");
        return mv;

Further above method in controller is defined as:

`private void authenticateUserAndSetSession(Users user, String passwor`dFromForm, HttpServletRequest request){

        String username = user.getUsername();
        System.out.println("username:  " + username + " password: " + passwordFromForm);                        

        UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, passwordFromForm, userDetails.getAuthorities());

        System.out.println("Line Authentication 1");

        usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(request));

        System.out.println("Line Authentication 2");

        Authentication authenticatedUser = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        System.out.println("Line Authentication 3");

        if (usernamePasswordAuthenticationToken.isAuthenticated()) {
            System.out.println("Line Authentication 4");


     request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());// creates context for that session.

        System.out.println("Line Authentication 5");

        session.setAttribute("username", user.getUsername());

        System.out.println("Line Authentication 6");

        session.setAttribute("authorities", usernamePasswordAuthenticationToken.getAuthorities());

        System.out.println("username:  " + user.getUsername() + "password: " + user.getPassword()+"authorities: "+ usernamePasswordAuthenticationToken.getAuthorities());

        user = userDAO.validate(user.getUsername(), user.getPassword());
        log.debug("You are successfully register");


Other answers didnt suggest to put it in try/catch so one does not realize why logic is not working as code runs...and nothing is there neither error or exception on console. So if you wont put it in try catch you wont get exception of bad credentials.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter