Search code examples
angularspringspring-securityangular-httpclient

Can't use Spring security /logout resource


I have a spring security app. When i try to log out via my angular front-end, I will get a 404 (Not found).

I have tried many spring WebSecurityConfigurerAdapter configurations, and i get a 404 with all of them. I am using POST to make my request.(see below)

logout() {
    this.http.post('/logout', "").pipe(
      finalize(() => {
        this.app.authenticated.next(false);
      })
    ).subscribe();
  }

Using Postman, i get a 403 (forbidden) when trying to reach the resource


Solution

  • In fact what you need is just to add a logout success handler

      @Component
    public class LogoutSuccess implements LogoutSuccessHandler {
    
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication)
            throws IOException, ServletException {
        if (authentication != null && authentication.getDetails() != null) {
            try {
                httpServletRequest.getSession().invalidate();
                // you can add more codes here when the user successfully logs
                // out,
                // such as updating the database for last active.
            } catch (Exception e) {
                e.printStackTrace();
                e = null;
            }
        }
    
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    
    }
    
    }
    

    and add a success handler to your security config

    http.authorizeRequests().anyRequest().authenticated().and().logout().logoutSuccessHandler(logoutSuccess).deleteCookies("JSESSIONID").invalidateHttpSession(false).permitAll();
    

    or you can also try this :

     logout() {
        this.http.post('/logout').pipe(
          finalize(() => {
            this.app.authenticated.next(false);
          })
        ).subscribe();
      }