Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security. How to log out user (revoke oauth2 token)

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?

like image 300
gstackoverflow Avatar asked Feb 24 '14 12:02

gstackoverflow


People also ask

How do I revoke auth token in Spring Security?

To revoke a valid access token, stop the Client Application from using that access token, we will use the token revocation endpoint. With the Authorization Server built using Spring Authorization Server, you can use the following POST request to revoke an access token: http://localhost:8080/oauth2/revoke.

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.

Should I revoke refresh token logout?

Yes you should. Because after logout when the user will login a new access token with a new refresh token will be issued. In that case, you should not keep your refresh token.

How do I manually revoke access 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.


1 Answers

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 
like image 160
camposer Avatar answered Oct 01 '22 02:10

camposer