This post explains how to customize the logout operation using Spring Security’s logoutSuccessHandler().
Along with a strong support for user authentication, the Spring Security framework also provides easier ways to implement the user logout process with hardly having any code in place
However, there may be cases in which we need to customize the default flow when a user is logged out of the application. Spring Security provides a LogoutSuccessHandler that can be customized as needed just like we discussed about the AuthenticationFailureHandler.
Lets’s jump into the code part:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//...
@Override
protected void configure(HttpSecurity http) throws Exception {
//...
.logout()
.logoutSuccessHandler(logoutSuccessHandler())
//..
}
//...
@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
return new CustomLogoutSuccessHandler();
}
}
Above code tells Spring Security that you have added a custom logout success handler. Now let’s create the CustomLogoutSuccessHandler class to perform any action after a successful logout.
public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication)
throws IOException, ServletException {
//get the current page's URL
String refererUrl = request.getHeader("Referer");
StringBuilder url = new StringBuilder("http://myapp.com");
//check the URL for role name and redirect to the corresponding login page
if(refererUrl.contains("/manager/"))
url.append("/manager/sign-in");
else if(refererUrl.contains("/admin/"))
url.append("/admin/sign-in");
response.sendRedirect(url.toString());
super.onLogoutSuccess(request, response, authentication);
}
}
CustomLogoutSuccessHandler class is our custom logout success handler. It extends SimpleUrlLogoutSuccessHandler of Spring Security which handles navigation on user logout. Our custom class also implements the LogoutSuccessHandler interface which handles redirection or forwarding to the appropriate destination.
In our custom code we simply check the user’s current page’s URL and redirect to appropriate login page. You can have your own customized code to serve the purpose.
To note:
- If you are configuring a logout success handler, the built-in logoutSuccessUrl() is not to be used along with it. It will be ignored even if provided.
- The LogoutSuccessHandler will be invoked only after a successful logout. So the user session will be null or empty.