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:
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.
You can apply this filter to the routes that need authentication. Route::filter('auth', function() { if (Auth::guest()) { return Redirect::guest('login'); } }); What this method basically does it's to store the page you were trying to visit and it is redirects you to the login page. return Redirect::intended();
Try a URL http://localhost:8080/HelloWeb/index and you should see the following result if everything is fine with your Spring Web Application. Click the "Redirect Page" button to submit the form and to get the final redirected page.
AuthenticationEntryPoint is used to send an HTTP response that requests credentials from a client. Sometimes a client will proactively include credentials such as a username/password to request a resource.
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>
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 ; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With