简体   繁体   English

如何删除令牌 JWT

[英]how to delete a token JWT

I'm working on authentication on spring framework using JWT, bearer token.我正在使用 JWT、不记名令牌对 spring 框架进行身份验证。

public String generateToken(UserProfile authentication) {

  // set the expiration time        
  Date now = new Date();
  Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);

  // Generate token and return      
  return Jwts.builder()
    .setSubject(authentication.getUsername())
    .claim("roles","user")
    .setIssuedAt(new Date())
    .setExpiration(expiryDate)
    .signWith(SignatureAlgorithm.HS512,jwtSecret)
    .compact();

The above class generates a token and respond back to the user.上面的类生成一个令牌并回复给用户。 My question is how I'm going to delete the token when a user issue a new token before the first token expire time;我的问题是当用户在第一个令牌到期时间之前发出新令牌时,我将如何删除令牌; to revoke the first token when a user request a new token before the first is expired?当用户在第一个令牌过期之前请求新令牌时撤销第一个令牌?

I don't think that's possible to do with JWT.我认为这与 JWT 无关。 You could你可以

  • Add the old one to some fast storage (like Redis or memcached)将旧的添加到一些快速存储(如 Redis 或 memcached)
  • Set some timeout on the value (a little big longer than the expire date of no longer wanted token)在值上设置一些超时(比不再需要令牌的到期日期长一点)
  • Check if the token from request exists in your cache, if yes then reject it检查来自请求的令牌是否存在于您的缓存中,如果是,则拒绝它

basically, do the blacklisting基本上,做黑名单

I'm not aware of any other solutions我不知道任何其他解决方案

If you use JWT, you can't revoque the token.如果您使用 JWT,则无法撤销令牌。 Its validity is embedded.它的有效性是嵌入的。

When you want to revoke a token, don't use JWT.当您要撤销令牌时,请不要使用 JWT。 You must persist the token and check its validity at every request.您必须保留令牌并在每次请求时检查其有效性。

If you really want to use it, save it in db as if it's not independent and add a flag or a timestamp for validity.如果您真的要使用它,请将其保存在 db 中,就好像它不是独立的一样,并添加一个标志或时间戳以确保有效性。

Check JWT documentation : https://jwt.io/检查 JWT 文档: https : //jwt.io/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM