Streetsouls Streetsouls - 1 year ago 161
Java Question

Spring Security logout does not work - does not clear security context and authenticated user still exists

I know, there are many articles about this topic, but I have a problem and I can't find any solution.

I have a classic spring security java config:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

private AuctionAuthenticationProvider auctionAuthenticationProvider;

public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

protected void configure(HttpSecurity http) throws Exception {

ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequest = http.authorizeRequests();


.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);


Also, I have two controller methods, where I login/logout from my web application by AJAX.

When I would like to logout, I first call this method, which I expect to clear user sessions and clear everything from the security context.

@RequestMapping(value = "/logout", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Boolean> logout(final HttpServletRequest request, final HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);

return new ResponseEntity<>(Boolean.TRUE, HttpStatus.OK);

After this I reload my client web application and each time, when it is reloaded, I check whether the user is authenticated by calling the following controller method:

@RequestMapping(value = "/user", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<UserDetails> user() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
return new ResponseEntity<>((UserDetails) principal, HttpStatus.OK);

return null;

And here I aways receive the last authenticated user. It seems that in the previous logout method, Spring logout doesn't work.

Keep in mind that I tried to logout with the following code, without any success:

@RequestMapping(value = "/logout", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Boolean> logout(final HttpServletRequest request) {
try {

return new ResponseEntity<>(Boolean.TRUE, HttpStatus.OK);
} catch (ServletException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("There is a problem with the logout of the user", ex);

Are you have any idea what I miss in my config and the logout process?

Answer Source

From your question,I see you are trying to create your own logout and you also trying to use the default spring logout.I advise you should choose one method only not mixed them both.There are two way I can show you to logout from spring:

First: Default spring security logout

.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))

From example above, you should only need to call the /logout url whenever you want to logout the user. No need to create any @Controller to handle that logout instead spring will help to log the user out. You also can add other thing you want to invalidate here.

Second: Proggrammatically logout

@RequestMapping(value = {"/logout"}, method = RequestMethod.POST)
public String logoutDo(HttpServletRequest request,HttpServletResponse response){
HttpSession session= request.getSession(false);
         session= request.getSession(false);
        if(session != null) {
        for(Cookie cookie : request.getCookies()) {

    return "logout";

If you are using this logout,you doesn't need to include the first method in spring security config. By using this method,you can add extra action to do before and after logout done.Btw, to use this logout ,just call the /logout url and user will be logout manually.This method will invalidate session,clear spring security context and cookies.

In addition for second method, if you are using RequestMethod.POST, you need to include the csrf key as a post. The alternative way is to create a form with hidden input csrf key. This is some example of auto generated logout link with jquery :


You just need to create hyperlink <a id="Logout">Logout</a> to use it.

If you are using RequestMethod.GET,just include a csrf key as a parameter in you link like this:

<a href="${pageContext.request.contextPath}/logout?${_csrf.parameterName}=${_csrf.token}">Logout</a>

Thats all,hope its help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download