应用场景
当用户登录状态到登出状态时,对应的jwt的令牌需要设置为失效状态,这时可以使用基于 redis 的黑名单方案来实现jwt令牌失效。
基于 redis 的黑名单方案
当用户需要登出系统时,将用户携带的token进行解析,解码出jwt令牌,取出对应的 uuid 和 过期时间 ,用过期的时间减去当前的时间,计算出这个key的过期时间,再以这两个字段拼接作为 key 并设置好过期时间存储到 redis 中,如果有黑客拿窃取出来的jwt令牌进行登录,只要判断这个jwt令牌是否在黑名单就可以。
实现步骤
1.获得携带的token解析并取出jwt令牌的代码
这段代码实现了对指定 jwt 的验证和使令牌失效的操作。
- 首先,通过调用 converttoken(headertoken) 方法将传入的头部令牌 headertoken 转换成实际的 jwt 字符串 token。
- 然后,使用 hmac256 算法和预设的密钥 key 创建一个算法实例 algorithm。
- 接下来,使用算法实例 algorithm 构建一个 jwt 验证器 jwtverifier。这个验证器将用于验证 jwt 的有效性。
- 在 try-catch 块中,首先通过调用 jwtverifier.verify(token) 方法对 jwt 进行验证。如果验证成功,则返回一个 decodedjwt 对象 verify,其中包含了 jwt 的解码信息,如令牌的唯一标识符(id)和过期时间等。
- 接着,调用 deletetoken(verify.getid(), verify.getexpiresat()) 方法来删除指定令牌,并将其加入到黑名单中进行失效处理。这里使用了 verify 对象中的 id 和过期时间作为参数。
- 最后,如果在验证 jwt 过程中发生了 jwtverificationexception 异常,即 jwt 验证失败,则捕获该异常,并返回 false 表示令牌失效操作失败。
/** * 让指定jwt令牌失效 * @param headertoken 请求头中携带的令牌 * @return 是否操作成功 */ public boolean invalidatejwt(string headertoken){ string token = this.converttoken(headertoken); algorithm algorithm = algorithm.hmac256(key); jwtverifier jwtverifier = jwt.require(algorithm).build(); try { decodedjwt verify = jwtverifier.verify(token); return deletetoken(verify.getid(), verify.getexpiresat()); } catch (jwtverificationexception e) { return false; } }
2.检查指定 uuid 的令牌是否为无效的(已加入黑名单)
这段代码用于检查指定 uuid 的令牌是否为无效的(已加入黑名单),通过判断 redis 数据库中是否存在相应的键来决定令牌的有效性。如果键存在,则表示令牌已失效;如果键不存在,则表示令牌仍然有效。
/** * 验证token是否被列入redis黑名单 * @param uuid 令牌id * @return 是否操作成功 */ private boolean isinvalidtoken(string uuid){ return boolean.true.equals(template.haskey(const.jwt_black_list + uuid)); }
3.将token列入redis黑名单中
这段代码实现了对指定令牌的删除和加入黑名单的操作,用于管理令牌的有效性和安全性。
- 首先,通过调用 isinvalidtoken(uuid) 方法来检查指定的 uuid 是否为无效的令牌。如果 isinvalidtoken 方法返回 true,则说明该令牌无效,此时直接返回 false,不执行后续操作。
- 获取当前时间 now,然后计算令牌的过期时间与当前时间的差值,并取最大值作为令牌的失效时间 expire。这里使用了 math.max 方法来确保失效时间不会小于 0。
- 最后,通过 redis 的 template 对象调用 opsforvalue().set() 方法,将指定 uuid 的令牌加入到名为 const.jwt_black_list + uuid 的键中,并设置过期时间为 expire 毫秒。这样就将该令牌加入到了黑名单中,使其在一定时间后失效。
- 最终,方法返回 true 表示成功删除令牌并将其加入黑名单。
/** * 将token列入redis黑名单中 * @param uuid 令牌id * @param time 过期时间 * @return 是否操作成功 */ private boolean deletetoken(string uuid, date time){ if(this.isinvalidtoken(uuid)) return false; date now = new date(); long expire = math.max(time.gettime() - now.gettime(), 0); template.opsforvalue().set(const.jwt_black_list + uuid, "", expire, timeunit.milliseconds); return true; }
public final class const { //jwt令牌 public final static string jwt_black_list = "jwt:blacklist:"; public final static string jwt_frequency = "jwt:frequency:"; }
对应完整的代码如下:
@component public class jwtutils { @autowired private stringredistemplate template; @value("${spring.security.jwt.key}") string key; @value("${spring.security.jwt.expire}") int expire; /** * 让指定jwt令牌失效 * @param headertoken 请求头中携带的令牌 * @return 是否操作成功 */ public boolean invalidatejwt(string headertoken){ string token = this.converttoken(headertoken); algorithm algorithm = algorithm.hmac256(key); jwtverifier jwtverifier = jwt.require(algorithm).build(); try { decodedjwt verify = jwtverifier.verify(token); return deletetoken(verify.getid(), verify.getexpiresat()); } catch (jwtverificationexception e) { return false; } } /** * 将token列入redis黑名单中 * @param uuid 令牌id * @param time 过期时间 * @return 是否操作成功 */ private boolean deletetoken(string uuid, date time){ if(this.isinvalidtoken(uuid)) return false; date now = new date(); long expire = math.max(time.gettime() - now.gettime(), 0); template.opsforvalue().set(const.jwt_black_list + uuid, "", expire, timeunit.milliseconds); return true; } /** * 验证token是否被列入redis黑名单 * @param uuid 令牌id * @return 是否操作成功 */ private boolean isinvalidtoken(string uuid){ return boolean.true.equals(template.haskey(const.jwt_black_list + uuid)); } public decodedjwt resolvejwt(string headertoken) { string token = this.converttoken(headertoken); if (token == null) { return null; } algorithm algorithm = algorithm.hmac256(key); jwtverifier jwtverifier = jwt.require(algorithm).build(); try { decodedjwt verify = jwtverifier.verify(token); if(this.isinvalidtoken(verify.getid())) return null; date expireat = verify.getexpiresat(); return new date().after(expireat) ? null : verify; } catch (jwtverificationexception e) { return null; } } public userdetails touser(decodedjwt jwt) { map<string, claim> claims = jwt.getclaims(); return user.withusername(claims.get("name").asstring()) .password("********") .authorities(claims.get("authorities").asarray(string.class)) .build(); } public integer toid(decodedjwt jwt) { map<string, claim> claims = jwt.getclaims(); return claims.get("id").asint(); } public string createjwt(userdetails details, int id, string username) { algorithm algorithm = algorithm.hmac256(key); date expire = this.expiretime(); return jwt.create() .withjwtid(uuid.randomuuid().tostring()) .withclaim("id", id) .withclaim("name", username) .withclaim("authorities", details.getauthorities().stream().map(grantedauthority::getauthority).tolist()) .withexpiresat(expire) .withissuedat(new date()) .sign(algorithm); } public date expiretime() { calendar calendar = calendar.getinstance(); calendar.add(calendar.hour, expire * 24); return calendar.gettime(); } private string converttoken(string headertoken) { if(headertoken == null || !headertoken.startswith("bearer ")) { return null; } return headertoken.substring(7); } }
到此这篇关于基于 redis 的 jwt令牌失效方案的文章就介绍到这了,更多相关redis jwt令牌失效内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论