Auto login after successful registration

前端 未结 10 2415
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 23:44

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 registrati

相关标签:
10条回答
  • 2020-11-29 00:18

    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);
    SecurityContextHolder.getContext().setAuthentication(auth);
    

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

    security-xml

    <form-login login-page="/login" 
                always-use-default-target="false" 
                default-target-url="/target-url" 
                authentication-failure-url="/login?error"
                login-processing-url="/submitLogin"/>
    

    web.xml

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/submitLogin</url-pattern>
        <dispatcher>FORWARD</dispatcher>
     </filter-mapping>
    

    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 讨论(0)
  • 2020-11-29 00:21

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

    import org.springframework.security.web.savedrequest.RequestCache;
    import org.springframework.security.web.savedrequest.SavedRequest;
    
    @Controller
    public class SignupController
    {
    
        @Autowired
        RequestCache requestCache;
    
        @Autowired
        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
            request.getSession();
    
            token.setDetails(new WebAuthenticationDetails(request));
            Authentication authenticatedUser = authenticationManager.authenticate(token);
    
            SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
        }
    }
    

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

    0 讨论(0)
  • 2020-11-29 00:23

    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"/>
      ...
    </http>
    
    0 讨论(0)
  • 2020-11-29 00:27

    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: http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#servletapi-3

    0 讨论(0)
  • 2020-11-29 00:27
    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:

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    
    <!-- Handle authentication for normal requests. -->
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- Handle authentication via forwarding for internal/automatic authentication. -->
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/login/auth</url-pattern>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    

    Source: mohchi blog

    0 讨论(0)
  • 2020-11-29 00:32

    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>
        <authentication-provider>
            <user-service>
                <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
                <user name="bob" password="bobspassword" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
    

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

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());
    request.getSession();
    
    token.setDetails(new WebAuthenticationDetails(request));
    
    try{
        Authentication auth = authenticationManager.authenticate(token);
    
        SecurityContextHolder.getContext().setAuthentication(auth);
    } catch(Exception e){
            e.printStackTrace();
    }
    
    return "redirect:xxxx.htm";
    
    0 讨论(0)
提交回复
热议问题