Reputation: 7451
I've got a web app that uses spring security. I'm wanting to redirect the user back to the same page they were on before log out when they log out.
Is there an easy way to do this?
Upvotes: 5
Views: 7412
Reputation: 4418
You can add a new filter in the filter chain of the spring security. That new filter will be applied to the /logout
URL. When going trough this filter you can save the current page in a field variable. And when returning through the filter. You can redirect the request to the saved URL. I think this can help. You can get the current page URL by using the Referer
header in the Request
object.
Upvotes: 1
Reputation: 226
What you need is a Simple LogoutSuccessHandler
@Component
public class CustomLogoutSuccessHandler extends
SimpleUrlLogoutSuccessHandler implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse
response, Authentication authentication)
throws IOException, ServletException {
if (authentication != null) {
System.out.println(authentication.getName());
}
response.setStatus(HttpStatus.OK.value());
response.sendRedirect(request.getHeader("referer"));
}
And later call it in your configure method i.e
.logout().logoutSuccessHandler(customLogoutSuccessHandler)
This will redirect you to referer URL.
Upvotes: 2
Reputation: 2271
Not sure which Spring version this question was referring to - but there is a useReferer
property on the standard org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler
since Spring 3.0.
So all you need to do is configure it like this and the logout will redirect to wherever the user came from:
<bean id="logoutSuccessHandler" class="org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler">
<property name="useReferer" value="true"/>
</bean>
<security:http>
<security:logout logout-url="/logout" success-handler-ref="logoutSuccessHandler" />
</security:http>
Upvotes: 7
Reputation: 240880
Just a thought:
How about we keep a stack of visited pages. may be at max 3 entries. and redirects user from logout.
Configure a Filter or extend spring security filter to maintain a stack in session about last two visited URLs
On logout configure a servlet as logout-success-url
.
Now get the URL from session stack and now invalidate the session and redirect user to that page
Also you can make use of referrer header as Vijay has mentioned
Upvotes: 0