Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to revoke auth token in spring security?

In logout controller I tryed to write a lot of combination of code. Now I have this:

final Authentication auth = SecurityContextHolder.getContext().getAuthentication();

if (auth != null) {
    new SecurityContextLogoutHandler().logout(request, response, auth);
}

SecurityContextHolder.getContext().setAuthentication(null);
auth.setAuthenticated(false);

But after provided code execution token still valid.

What do I wrong? How to revoke token eventually?

like image 333
gstackoverflow Avatar asked Feb 24 '14 15:02

gstackoverflow


People also ask

How do I revoke OAuth access token?

To revoke a refresh token, send a POST request to https://YOUR_DOMAIN/oauth/revoke . The /oauth/revoke endpoint revokes the entire grant, not just a specific token. Use the /api/v2/device-credentials endpoint to revoke refresh tokens.

Can we revoke access token?

Once issued, access tokens and ID tokens cannot be revoked in the same way as cookies with session IDs for server-side sessions. As a result, tokens should be issued for relatively short periods, and then refreshed periodically if the user remains active.

How do you revoke a JWT token?

The most common way to revoke access to resources protected by a JWT involves setting its duration to a short period of time and revoking the refresh token so that the user can't generate a new token. This does not revoke the JWT per se; it does solve the root issue, which is to limit access.

How do I revoke an API token?

To revoke an access token, specify type accesstoken. To revoke both the access and refresh tokens, specify type refreshtoken. When it sees type refreshtoken, Edge assumes the token is a refresh token. If that refresh token is found, then it is revoked.


2 Answers

The class you're looking for is DefaultServices, method revokeToken(String tokenValue).

Here an exemple of a controller that revokes token, and here the oauth2 configuration with the DefaultServices bean.

like image 110
raonirenosto Avatar answered Sep 26 '22 07:09

raonirenosto


If you need to revoke a token for another user than the current one (E.g. an admin wants to disable a user account), you can use this:

Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientIdAndUserName(
                                                           "my_oauth_client_id", 
                                                           user.getUsername());
for (OAuth2AccessToken token : tokens) {
  consumerTokenServices.revokeToken(token.getValue());
}

With tokenStore being an org.springframework.security.oauth2.provider.token.TokenStore and consumerTokenServices being a org.springframework.security.oauth2.provider.token.ConsumerTokenServices

like image 22
Wim Deblauwe Avatar answered Sep 25 '22 07:09

Wim Deblauwe