Spring Security redirect to previous page after successful login

123,185

Solution 1

What happens after login (to which url the user is redirected) is handled by the AuthenticationSuccessHandler.

This interface (a concrete class implementing it is SavedRequestAwareAuthenticationSuccessHandler) is invoked by the AbstractAuthenticationProcessingFilter or one of its subclasses like (UsernamePasswordAuthenticationFilter) in the method successfulAuthentication.

So in order to have an other redirect in case 3 you have to subclass SavedRequestAwareAuthenticationSuccessHandler and make it to do what you want.


Sometimes (depending on your exact usecase) it is enough to enable the useReferer flag of AbstractAuthenticationTargetUrlRequestHandler which is invoked by SimpleUrlAuthenticationSuccessHandler (super class of SavedRequestAwareAuthenticationSuccessHandler).

<bean id="authenticationFilter"
      class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
    <property name="filterProcessesUrl" value="/login/j_spring_security_check" />
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationSuccessHandler">
        <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
            <property name="useReferer" value="true"/>
        </bean>
    </property>
    <property name="authenticationFailureHandler">
        <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
            <property name="defaultFailureUrl" value="/login?login_error=t" />
        </bean>
    </property>
</bean>

Solution 2

I want to extend Olcay's nice answer. His approach is good, your login page controller should be like this to put the referrer url into session:

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(HttpServletRequest request, Model model) {
    String referrer = request.getHeader("Referer");
    request.getSession().setAttribute("url_prior_login", referrer);
    // some other stuff
    return "login";
}

And you should extend SavedRequestAwareAuthenticationSuccessHandler and override its onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) method. Something like this:

public class MyCustomLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    public MyCustomLoginSuccessHandler(String defaultTargetUrl) {
        setDefaultTargetUrl(defaultTargetUrl);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        HttpSession session = request.getSession();
        if (session != null) {
            String redirectUrl = (String) session.getAttribute("url_prior_login");
            if (redirectUrl != null) {
                // we do not forget to clean this attribute from session
                session.removeAttribute("url_prior_login");
                // then we redirect
                getRedirectStrategy().sendRedirect(request, response, redirectUrl);
            } else {
                super.onAuthenticationSuccess(request, response, authentication);
            }
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}

Then, in your spring configuration, you should define this custom class as a bean and use it on your security configuration. If you are using annotation config, it should look like this (the class you extend from WebSecurityConfigurerAdapter):

@Bean
public AuthenticationSuccessHandler successHandler() {
    return new MyCustomLoginSuccessHandler("/yourdefaultsuccessurl");
}

In configure method:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            // bla bla
            .formLogin()
                .loginPage("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(successHandler())
                .permitAll()
            // etc etc
    ;
}

Solution 3

I have following solution and it worked for me.

Whenever login page is requested, write the referer value to the session:

@RequestMapping(value="/login", method = RequestMethod.GET)
public String login(ModelMap model,HttpServletRequest request) {

    String referrer = request.getHeader("Referer");
    if(referrer!=null){
        request.getSession().setAttribute("url_prior_login", referrer);
    }
    return "user/login";
}

Then, after successful login custom implementation of SavedRequestAwareAuthenticationSuccessHandler will redirect user to the previous page:

HttpSession session = request.getSession(false);
if (session != null) {
    url = (String) request.getSession().getAttribute("url_prior_login");
}

Redirect the user:

if (url != null) {
    response.sendRedirect(url);
}

Solution 4

I've custom OAuth2 authorization and request.getHeader("Referer") is not available at poit of decision. But security request already saved in ExceptionTranslationFilter.sendStartAuthentication:

protected void sendStartAuthentication(HttpServletRequest request,...
    ...
    requestCache.saveRequest(request, response);

So, all what we need is share requestCache as Spring bean:

@Bean
public RequestCache requestCache() {
   return new HttpSessionRequestCache();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
   ... 
   .requestCache().requestCache(requestCache()).and()
   ...
}     

and use it wheen authorization is finished:

@Autowired
private RequestCache requestCache;

public void authenticate(HttpServletRequest req, HttpServletResponse resp){
    ....
    SavedRequest savedRequest = requestCache.getRequest(req, resp);
    resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?  
    savedRequest.getRedirectUrl() : "defaultURL");
}
Share:
123,185
Christos Loupassakis
Author by

Christos Loupassakis

Updated on July 08, 2022

Comments

  • Christos Loupassakis
    Christos Loupassakis almost 2 years

    I know this question has been asked before, however I'm facing a particular issue here.

    I use spring security 3.1.3.

    I have 3 possible login cases in my web application:

    1. Login via the login page : OK.
    2. Login via a restricted page : OK too.
    3. Login via a non-restricted page : not OK... a "product" page can be accessed by everybody, and a user can post a comment if he's logged. So a login form is contained in the same page in order to allow users to connect.

    The problem with case 3) is that I can't manage to redirect users to the "product" page. They get redirected to the home page after a successful login, no matter what.

    Notice that with case 2) the redirection to the restricted page works out of the box after successful login.

    Here's the relevant part of my security.xml file:

    <!-- Authentication policy for the restricted page  -->
    <http use-expressions="true" auto-config="true" pattern="/restrictedPage/**">
        <form-login login-page="/login/restrictedLogin" authentication-failure-handler-ref="authenticationFailureHandler" />
        <intercept-url pattern="/**" access="isAuthenticated()" />
    </http>
    
    <!-- Authentication policy for every page -->
    <http use-expressions="true" auto-config="true">
        <form-login login-page="/login" authentication-failure-handler-ref="authenticationFailureHandler" />
        <logout logout-url="/logout" logout-success-url="/" />
    </http>
    

    I suspect the "authentication policy for every page" to be responsible for the problem. However, if I remove it I can't login anymore... j_spring_security_check sends a 404 error.


    EDIT:

    Thanks to Ralph, I was able to find a solution. So here's the thing: I used the property

    <property name="useReferer" value="true"/>
    

    that Ralph showed me. After that I had a problem with my case 1) : when logging via the login page, the user stayed in the same page (and not redirected to the home page, like it used to be). The code until this stage was the following:

    <!-- Authentication policy for login page -->
    <http use-expressions="true" auto-config="true" pattern="/login/**">
        <form-login login-page="/login" authentication-success-handler-ref="authenticationSuccessHandlerWithoutReferer" />
    </http>
    
    <!-- Authentication policy for every page -->
    <http use-expressions="true" auto-config="true">
        <form-login login-page="/login" authentication-failure-handler-ref="authenticationFailureHandler" />
        <logout logout-url="/logout" logout-success-url="/" authentication-success-handler-ref="authenticationSuccessHandler"/>
    </http>
    
    <beans:bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
        <!-- After login, return to the last visited page -->
        <beans:property name="useReferer" value="true" />
    </beans:bean>
    
    <beans:bean id="authenticationSuccessHandlerWithoutReferer" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
        <!-- After login, stay to the same page -->
        <beans:property name="useReferer" value="false" />
    </beans:bean>
    

    This should work, in theory at least, but it wasn't. I still dont know why, so if someone has an answer on this, I will gladly create a new topic to allo him to share his solution.

    In the meantime, I came to a workaround. Not the best solution, but like I said, if someone has something better to show, I'm all ears. So this is the new authentication policy for the login page :

    <http use-expressions="true" auto-config="true" pattern="/login/**" >
        <intercept-url pattern="/**" access="isAnonymous()" />
        <access-denied-handler error-page="/"/>
    </http>
    

    The solution here is pretty obvious: the login page is allowed only for anonymous users. Once a user is connected, the error handler redirects him to the home page.

    I did some tests, and everything seems to be working nicely.

  • Christos Loupassakis
    Christos Loupassakis over 11 years
    There's no possibility to use entirely xml configuration ? And how do I manage to store the last visited page ?
  • Ralph
    Ralph over 11 years
    You mean that you do not want to create a subclass of the SavedRequestAwareAuthenticationSuccessHandler?
  • Christos Loupassakis
    Christos Loupassakis over 11 years
    Yes if possible. However, if it's not possible, could you provide an implementation example ?
  • Ralph
    Ralph over 11 years
    @Christos Loupassakis extending SavedRequestAwareAuthenticationSuccessHandler should be very easy, the onAuthenticationSuccess mehtod only 30 lines long, so have a look at the code.
  • Ralph
    Ralph over 11 years
    @Christos Loupassakis: but maybe the useReferer attribute is what you need - see my extended answer
  • Christos Loupassakis
    Christos Loupassakis over 11 years
    Thanks ! useReferer is exactly what I need ! Now my case 3) works fine but... case 1) does not work anymore : when I login from the login page, I stay in the login page (I used to be redirected to home page). Even if I specify a "authentication-success-handler-ref" for my login page with "useReferer = false" the result is the same. This is giving me headaches. Anyway, I'm looking forward to this problem and I'll validate your answer soon, even if I can't manage that (it looks like a different matter).
  • Christos Loupassakis
    Christos Loupassakis over 11 years
    After digging a lot, it seems that the embedded login form in case 3) is the problem. In my initial configuration (without "useReferer") if a restrict the whole "product" page, after login the redirection is successful. But this page can't be restricted, it's a public page where users can login among other things. That's really troublesome, I wonder if spring security just can't handle this case (which seems a pretty common case to me anyway ! same applies on stackoverflow for example !) or if it's me doing it wrong.
  • Christos Loupassakis
    Christos Loupassakis over 11 years
    Ok I found a workaround ! It's more a "quick-and-dirty" solution, but for now it works. I'll edit my original post to show it. If any idea on how to get it better, I'm all ears :) In the meantime, I valid your answer.
  • azerafati
    azerafati almost 10 years
    This was a great idea thanks for completing the answer, and in your onAuthenticationSuccess session will never be null so no need to check that .getSession() will never return null
  • Jack Straw
    Jack Straw about 6 years
    Thank you for this answer. It helped. However, I'm trying to add a cookie containing a JWT to the response. Looks like it is adding that cookie to the response for /j_spring_security_check, but not for the response to the redirect.
  • kangear
    kangear over 3 years
    only url without query param
  • kangear
    kangear over 3 years