33

When I want to get logout I invoke this code:

request.getSession().invalidate();
SecurityContextHolder.getContext().setAuthentication(null);

But after it (in next request using old oauth token) I invoke

SecurityContextHolder.getContext().getAuthentication();

and I see my old user there.

How to fix it?

0

11 Answers 11

43

Here's my implementation (Spring OAuth2):

@Controller
public class OAuthController {
    @Autowired
    private TokenStore tokenStore;

    @RequestMapping(value = "/oauth/revoke-token", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public void logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            String tokenValue = authHeader.replace("Bearer", "").trim();
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
            tokenStore.removeAccessToken(accessToken);
        }
    }
}

For testing:

curl -X GET -H "Authorization: Bearer $TOKEN" http://localhost:8080/backend/oauth/revoke-token
8
  • If you don't want to remove access token (remember you can always change the query!) you may want to user DefaultServices (if you're using it)
    – camposer
    Aug 31, 2015 at 22:30
  • 4
    You can directly use ConsumerTokenServices's revoke functions
    – Ming
    Nov 5, 2015 at 16:53
  • I am trying to implement your suggestion in a github sample app. Are you willing to take a look? Here is the link: stackoverflow.com/questions/36683434/…
    – CodeMed
    Apr 18, 2016 at 0:56
  • @Ming, I'm revoking access token using ConsumerTokenServices on logout, but the next login attempt directly taking me to OAuth Approval page instead of full authentication. Is it necessary to remove token from browser also?
    – rsinha
    Jan 30, 2018 at 15:07
  • 2
    Instead of HttpServletRequest as parameter, you can use @RequestHeader(value="Authorization") String authHeader directly Mar 2, 2018 at 16:48
12

The response by camposer can be improved using the API provided by Spring OAuth. In fact, it's not necessary to access directly to the HTTP headers, but the REST method which removes the access token can be implemented as follows:

@Autowired
private AuthorizationServerTokenServices authorizationServerTokenServices;

@Autowired
private ConsumerTokenServices consumerTokenServices;

@RequestMapping("/uaa/logout")
public void logout(Principal principal, HttpServletRequest request, HttpServletResponse response) throws IOException {

    OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
    OAuth2AccessToken accessToken = authorizationServerTokenServices.getAccessToken(oAuth2Authentication);
    consumerTokenServices.revokeToken(accessToken.getValue());

    String redirectUrl = getLocalContextPathUrl(request)+"/logout?myRedirect="+getRefererUrl(request);
    log.debug("Redirect URL: {}",redirectUrl);

    response.sendRedirect(redirectUrl);

    return;
}

I also added a redirect to the endpoint of Spring Security logout filter, so the session is invalidated and the client must provide credentials again in order to access to the /oauth/authorize endpoint.

1
  • I tried same thing it return 200 response, but still i'm able to use same token and access the data. Feb 21, 2020 at 11:44
6

It depends on type of oauth2 'grant type' that you're using.

The most common if your have used spring's @EnableOAuth2Sso in your client app is 'Authorization Code'. In this case Spring security redirects login request to the 'Authorization Server' and creates a session in your client app with the data received from 'Authorization Server'.

You can easy destroy your session at the client app calling /logout endpoint, but then client app sends user again to 'authorization server' and returns logged again.

I propose to create a mechanism to intercept logout request at client app and from this server code, call "authorization server" to invalidate the token.

The first change that we need is create one endpoint at the authorization server, using the code proposed by Claudio Tasso, to invalidate the user's access_token.

@Controller
@Slf4j
public class InvalidateTokenController {


    @Autowired
    private ConsumerTokenServices consumerTokenServices;


    @RequestMapping(value="/invalidateToken", method= RequestMethod.POST)
    @ResponseBody
    public Map<String, String> logout(@RequestParam(name = "access_token") String accessToken) {
        LOGGER.debug("Invalidating token {}", accessToken);
        consumerTokenServices.revokeToken(accessToken);
        Map<String, String> ret = new HashMap<>();
        ret.put("access_token", accessToken);
        return ret;
    }
}

Then at the client app, create a LogoutHandler:

@Slf4j
@Component
@Qualifier("mySsoLogoutHandler")
public class MySsoLogoutHandler implements LogoutHandler {

    @Value("${my.oauth.server.schema}://${my.oauth.server.host}:${my.oauth.server.port}/oauth2AuthorizationServer/invalidateToken")
    String logoutUrl;

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

        LOGGER.debug("executing MySsoLogoutHandler.logout");
        Object details = authentication.getDetails();
        if (details.getClass().isAssignableFrom(OAuth2AuthenticationDetails.class)) {

            String accessToken = ((OAuth2AuthenticationDetails)details).getTokenValue();
            LOGGER.debug("token: {}",accessToken);

            RestTemplate restTemplate = new RestTemplate();

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("access_token", accessToken);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "bearer " + accessToken);

            HttpEntity<String> request = new HttpEntity(params, headers);

            HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
            HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();
            restTemplate.setMessageConverters(Arrays.asList(new HttpMessageConverter[]{formHttpMessageConverter, stringHttpMessageConverternew}));
            try {
                ResponseEntity<String> response = restTemplate.exchange(logoutUrl, HttpMethod.POST, request, String.class);
            } catch(HttpClientErrorException e) {
                LOGGER.error("HttpClientErrorException invalidating token with SSO authorization server. response.status code: {}, server URL: {}", e.getStatusCode(), logoutUrl);
            }
        }


    }
}

And register it at WebSecurityConfigurerAdapter:

@Autowired
MySsoLogoutHandler mySsoLogoutHandler;

@Override
public void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http
        .logout()
            .logoutSuccessUrl("/")
            // using this antmatcher allows /logout from GET without csrf as indicated in
            // https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-logout
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            // this LogoutHandler invalidate user token from SSO
            .addLogoutHandler(mySsoLogoutHandler)
    .and()
            ...
    // @formatter:on
}

One note: If you're using JWT web tokens, you can't invalidate it, because the token is not managed by the authorization server.

1
  • In case of JWT, yes you are right. Do you know a way to configure the auth server not to create session at all ( it uses session to store oauth client credential during the 'oauth dance' ) and use request param instead. Jan 24, 2017 at 13:33
3

Its up to your Token Store Implementation.

If you use JDBC token store then you just need to remove it from table... Anyway you must add /logout endpoint manually then call this :

@RequestMapping(value = "/logmeout", method = RequestMethod.GET)
@ResponseBody
public void logmeout(HttpServletRequest request) {
    String token = request.getHeader("bearer ");
    if (token != null && token.startsWith("authorization")) {

        OAuth2AccessToken oAuth2AccessToken = okenStore.readAccessToken(token.split(" ")[1]);

        if (oAuth2AccessToken != null) {
            tokenStore.removeAccessToken(oAuth2AccessToken);
        }
}
2
  • I am using JDBC token store, can you guide that how can I get tokenStore for last line "tokenStore.removeAccessToken(oAuth2AccessToken);" ? Jul 24, 2019 at 9:51
  • 1
    @ChiragShah As I remember I couldn't reach my goal by this approach, please trace current error the see the correct implementation:(No matter whats your token store type) github.com/spring-guides/tut-spring-security-and-angular-js/…
    – Pasha GR
    Jul 24, 2019 at 10:36
1

Programmatically you can log out this way:

public void logout(HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      if (auth != null){    
         new SecurityContextLogoutHandler().logout(request, response, auth);
      }
    SecurityContextHolder.getContext().setAuthentication(null);
}
0
0

Add following line in <http></http> tag.

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

This will delete JSESSIONID and invalidate session. And link to logout button or label would be something like:

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

EDIT: You want to invalidate session from java code. I assume you have to do some task right before logging the user out, and then invalidate session. If this is the use case, you should use custome logout handlers. Visit this site for more information.

3
  • Why are you doing it from Java code? Any specific use case? Feb 24, 2014 at 12:32
  • Yes. specific use case. Feb 24, 2014 at 12:33
  • See the edit. I guess you have to do something before logout process. You can write logout handlers to do such tasks. Feb 24, 2014 at 12:36
0

This works for Keycloak Confidential Client logout. I have no idea why the folks over at keycloak don't have more robust docs on java non-web clients and their endpoints in general, I guess that's the nature of the beast with open source libs. I had to spend a bit of time in their code:

    //requires a Keycloak Client to be setup with Access Type of Confidential, then using the client secret
public void executeLogout(String url){

    HttpHeaders requestHeaders = new HttpHeaders();
    //not required but recommended for all components as this will help w/t'shooting and logging
    requestHeaders.set( "User-Agent", "Keycloak Thick Client Test App Using Spring Security OAuth2 Framework");
    //not required by undertow, but might be for tomcat, always set this header!
    requestHeaders.set( "Accept", "application/x-www-form-urlencoded" );

    //the keycloak logout endpoint uses standard OAuth2 Basic Authentication that inclues the
    //Base64-encoded keycloak Client ID and keycloak Client Secret as the value for the Authorization header
     createBasicAuthHeaders(requestHeaders);

    //we need the keycloak refresh token in the body of the request, it can be had from the access token we got when we logged in:
    MultiValueMap<String, String> postParams = new LinkedMultiValueMap<String, String>();
    postParams.set( OAuth2Constants.REFRESH_TOKEN, accessToken.getRefreshToken().getValue() );

    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(postParams, requestHeaders);
    RestTemplate restTemplate = new RestTemplate();
    try {
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        System.out.println(response.toString());

    } catch (HttpClientErrorException e) {
        System.out.println("We should get a 204 No Content - did we?\n" + e.getMessage());          
    }
} 

//has a hard-coded client ID and secret, adjust accordingly
void createBasicAuthHeaders(HttpHeaders requestHeaders){
     String auth = keycloakClientId + ":" + keycloakClientSecret;
     byte[] encodedAuth = Base64.encodeBase64(
        auth.getBytes(Charset.forName("US-ASCII")) );
     String authHeaderValue = "Basic " + new String( encodedAuth );
     requestHeaders.set( "Authorization", authHeaderValue );
}
1
  • FYI: this was tested on Keylcoak 2.4.0 FINAL.
    – heregear
    Jan 6, 2017 at 15:19
0

Solution provided by user composer perfectly worked for me. I made some minor changes to the code as follows,

@Controller
public class RevokeTokenController {

    @Autowired
    private TokenStore tokenStore;

    @RequestMapping(value = "/revoke-token", method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<HttpStatus> logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            try {
                String tokenValue = authHeader.replace("Bearer", "").trim();
                OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
                tokenStore.removeAccessToken(accessToken);
            } catch (Exception e) {
                return new ResponseEntity<HttpStatus>(HttpStatus.NOT_FOUND);
            }           
        }

        return new ResponseEntity<HttpStatus>(HttpStatus.OK);
    }
}

I did this because If you try to invalidate same access token again, it throws Null Pointer exception.

1
  • I tried same thing it return 200 response, but still i'm able to use the same token and access the data.
    – Pavan
    Jul 1, 2020 at 11:46
0

At AuthServer

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
    throws Exception {
  ...
  endpoints.addInterceptor(new HandlerInterceptorAdapter() {
    @Override
    public void postHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
      if (modelAndView != null
          && modelAndView.getView() instanceof RedirectView) {
        RedirectView redirect = (RedirectView) modelAndView.getView();
        String url = redirect.getUrl();
        if (url.contains("code=") || url.contains("error=")) {
          HttpSession session = request.getSession(false);
          if (session != null) {
            session.invalidate();
          }
        }
      }
    }
  });
}

At client site

.and()
.logout().logoutSuccessUrl("/").permitAll()
.and().csrf()
.ignoringAntMatchers("/login", "/logout")
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

Seems a better solutions for me. referred this link

0

for logout token with spring boot rest security and oauth2.0 user as follow

import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;

@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    /**
     * Logout. This method is responsible for logout user from application based on
     * given accessToken.
     * 
     * @param accessToken the access token
     * @return the response entity
     */
    @GetMapping(value = "/oauth/logout")
    public ResponseEntity<Response> logout(@RequestParam(name = "access_token") String accessToken) {
        consumerTokenServices.revokeToken(accessToken);
        return new ResponseEntity<>(new Response(messageSource.getMessage("server.message.oauth.logout.successMessage",  null, LocaleContextHolder.getLocale())), HttpStatus.OK);

    }
}
0

You can remove both access token and refresh token from database to save the space.

    @PostMapping("/oauth/logout")
public ResponseEntity<String> revoke(HttpServletRequest request) {
    try {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.contains("Bearer")) {
            String tokenValue = authorization.replace("Bearer", "").trim();

            OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
            tokenStore.removeAccessToken(accessToken);

            //OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(tokenValue);
            OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
            tokenStore.removeRefreshToken(refreshToken);
        }
    } catch (Exception e) {
        return ResponseEntity.badRequest().body("Invalid access token");
    }

    return ResponseEntity.ok().body("Access token invalidated successfully");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.