How to pass parameter along with logout success url in spring security

logoutspring-security

I am using java based spring security configuration in my spring boot application. When user clicks on logout link, user is redirected to the login page. Here, in this case, I need to pass a custom parameter in the logout success url.

e.g. when I logout, app is redirected to http://localhost:8080/app/login
But I want it to have a parameter like below
http://localhost:8080/app/login?idletimeout=true

I have created my custom LogoutSuccesshandle for this. I get the param value in the handler and then I construct the success url and then redirect to it. But then on logout that parameter goes missing.

Below is my handler code.

public class LogoutSuccessHandlerImpl extends SimpleUrlLogoutSuccessHandler {

    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        request.getSession().invalidate();
        SecurityContextHolder.clearContext();

        request.setAttribute("isLoggedOut", "true");

        String contextPath = request.getContextPath();
        String redirectURL = "/login";

        String isIdleTimeOut = request.getParameter("idleTimeout");
        request.setAttribute("idleTimeout", isIdleTimeOut);

        System.out.println(isIdleTimeOut + " isIdleTimeOut ");

        if (isIdleTimeOut != null && isIdleTimeOut.equalsIgnoreCase("true")) {
            System.out.println("in if ");
            redirectURL += "?idleTimeout=" + isIdleTimeOut;
        }

        // setDefaultTargetUrl(redirectURL);
        // response.sendRedirect(redirectURL);
       // super.onLogoutSuccess(request, response, authentication);
        redirectStrategy.sendRedirect(request, response, redirectURL);
    }

Below is my java config code.

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
        .and()
            .formLogin()
            .loginPage("/login")
            .loginProcessingUrl("/checkLogin")
            .defaultSuccessUrl("/home")
            .failureUrl("/login?login_error=1")
            .usernameParameter("username")
            .passwordParameter("password")
            .permitAll()
        .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessHandler(new LogoutSuccessHandlerImpl())
            .deleteCookies("JSESSIONID")
            .invalidateHttpSession(true)
            .permitAll()
        .and()
            .authorizeRequests()
            .antMatchers("/login**").permitAll()
            .antMatchers("/error**").permitAll()
            .antMatchers("/checkLogin**").permitAll()
            .anyRequest()
            .authenticated()
            .accessDecisionManager(accessDecisionManager)
        .and()
            .exceptionHandling()
            .accessDeniedPage("/accessDenied")
        .and()
            .headers()
            .frameOptions()
            .disable()
        .and()
            .sessionManagement()
            .invalidSessionUrl("/login")
            .maximumSessions(1);
    }

Best Answer

What you can do is to prepare your own logout method (a custom logout url) for your applicatoin:

1) Prepare your LogoutController:

@Controller
@RequestMapping(value = "/logout")
public class LogoutController {

    @RequestMapping(value = {"", "/"})
    public String logout(HttpServletRequest request) {
        SecurityContextHolder.clearContext();
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return "redirect:" + <your-logout-success-url>;
    }

}

Here, invalidating the session and clearing the context provides you a logout mechanism.

2) Update your logout urls inside jsp files:

<a href="/logout" id="logout_" title="Log out"><span>Log out</span></a>

3) In addition, for default "log out" scenarios, you can still continue to use the Spring Security log out:

<logout logout-success-url="/" invalidate-session="true" delete-cookies="JSESSIONID"
            logout-url="/j_spring_security_logout"/>

So, in this logout method, you can do whatever you want with the request object when user demands the logout process. You do not need to pass parameters now.

Related Topic