退出登录时令JsonWebToken失效

有白名单,黑名单方式,建议使用黑名单,好处是消耗资源少, 减轻服务器压力。

黑名单实现方式如下:
1.在退出接口中加上如下示例:

// 引入相关
// import cn.hutool.jwt.JWT;
// import cn.hutool.jwt.JWTUtil;
// import java.time.*;

try{
	JWT jwt = JWTUtil.parseToken(token);
	cn.hutool.json.JSONObject jsonObject = jwt.getPayloads();
	String jti = (String) jsonObject.get("jti");
	// 过期时间
	Long exp = jsonObject.getLong("exp");
	// 将 Unix 时间戳转换为 Instant 对象
	Instant expirationTime = Instant.ofEpochSecond(exp);
	// 获取当前时间
	Instant now = Instant.now();
	// 计算剩余时间
	Duration remainingTime = Duration.between(now, expirationTime);
    
    // 设置exp过期时间为key的过期时间
	redisUtils.set(CacheNames.JTI_PREFIX + jti, "", remainingTime.getSeconds());
}catch (Exception e){
	logger.error("设置黑名单失败", e);
}
  1. 使用 redisTemplate 需要先序列化
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {

	@Bean
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<Object, Object> template = new RedisTemplate();
		template.setConnectionFactory(redisConnectionFactory);
		//设置key的序列化方式
		template.setKeySerializer(RedisSerializer.string());
		template.setHashKeySerializer(RedisSerializer.string());
		//设置值的序列化方式
		template.setValueSerializer(RedisSerializer.json());
		template.setHashValueSerializer(RedisSerializer.json());
		return template;
	}

}

3.找到鉴权相关代码

(下图是shiro相关的自定义过滤器)
在这里插入图片描述

4.在过滤器中加黑名单判断
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值