Virat
Virat

Reputation: 581

Logout in spring security without redirecting anywhere

Hi I implimented spring security in my spring boot application. But on clicking logout it needs some redirect url. How to avoid it?

My WebSecurityConfig is

@Override
protected void configure( HttpSecurity http ) throws Exception
{
    http.csrf().disable()

            .authorizeRequests()

            .antMatchers(HttpMethod.POST, "/rest/auth/**").permitAll()

            .antMatchers("/login").permitAll()

            .antMatchers("/").permitAll()

            .antMatchers("/dist/**").permitAll()

            .antMatchers("/node_modules/**").permitAll()

            .antMatchers("/src/**").permitAll()

            .anyRequest().authenticated()

            .and()

            .logout().addLogoutHandler(logoutHandler)

            .and()

            .addFilter(new JWTAuthenticationFilter(authenticationManager()))

            .addFilter(new JWTAuthorizationFilter(authenticationManager()));

    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

}

My LogoutHandler is

@Override
public void logout( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        Authentication authentication )
{

    try
    {
        SecurityContextHolder.getContext().setAuthentication(null);
        SecurityContextHolder.clearContext();
        String responseValue = new ObjectMapper().writeValueAsString("success");
        httpServletResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
        httpServletResponse.addHeader("Content-Type", "application/json");
        httpServletResponse.getWriter().print(responseValue);
    }
    catch( Exception e )
    {
        LOGGER.error("Error", e);
        String responseValue;
        try
        {
            responseValue = new ObjectMapper().writeValueAsString("failed");
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            httpServletResponse.addHeader("Content-Type", "application/json");
            httpServletResponse.getWriter().print(responseValue);
        }
        catch( IOException e1 )
        {
            LOGGER.error("Error", e1);
        }
    }
}

I just want the response to be sent to the client side as configured in LogoutHandler. But after successful logout, it is redirecting to /login. I don't want it to be redirected to any other url. I just want the response be sent to client side. How to achieve this?

Upvotes: 1

Views: 1418

Answers (1)

Leffchik
Leffchik

Reputation: 2030

Try this:

...
.and()
.logout().logoutSuccessHandler(logoutHandler)
.and()
...

Upvotes: 2

Related Questions