8.3JWT提前撤回

8.3JWT提前撤回

当遇到用户被删除、用户在另一个设备上登陆等场景需要将JWT提前撤回,但是JWT是保存在客户端,无法在服务器中进行删除。

解决思路是在用户表中增加一列JWTVersion,用来存储最后一次发放出去的令牌版本号,每次登陆、发放令牌的时候都让JWTVersion自增,当服务器收到客户端提交的JWT后,将客户端的JWTVersion和服务器的进行比较,如果客户端的值小于服务器中的值则过期。

实现步骤:

  1. 为实体类User增加一个long类型的属性JWTVersion
  2. 修改产生JWT的代码,实现JWTVersion自增
user.JWTVersion++;
await userManager.UpdateAsync(user);//更新数据库
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
claims.Add(new Claim(ClaimTypes.Version, user.JWTVersion.ToString()));//增加该信息
  1. 编写筛选器,统一实现对所有控制器操作方法中JWT的检查工作
public class JWTValidationFilter : IAsyncActionFilter
{
    private IMemoryCache memCache;
    private UserManager<User> userMgr;

    public JWTValidationFilter(IMemoryCache memCache, UserManager<User> userMgr)
    {
        this.memCache = memCache;
        this.userMgr = userMgr;
    }

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var claimUserId = context.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier);//查询用户信息
        //对于登录接口等没有登录的,直接跳过
        if (claimUserId == null)
        {
            await next();
            return;
        }
        long userId = long.Parse(claimUserId!.Value);
        //放到内存缓存中
        string cacheKey = $"JWTValidationFilter.UserInfo.{userId}";
        User user = await memCache.GetOrCreateAsync(cacheKey, async e => {
            e.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5);
            return await userMgr.FindByIdAsync(userId.ToString());
        });
        if (user == null)//为查找到用户,可能已经别删除
        {
            var result = new ObjectResult($"UserId({userId}) not found");
            result.StatusCode = (int)HttpStatusCode.Unauthorized;
            context.Result = result;
            return;
        }
        var claimVersion = context.HttpContext.User.FindFirst(ClaimTypes.Version);
        //jwt中保存的版本号
        long jwtVerOfReq = long.Parse(claimVersion!.Value);
        //由于内存缓存等导致的并发问题,
        //假如集群的A服务器中缓存保存的还是版本为5的数据,但客户端提交过来的可能已经是版本号为6的数据。因此只要是客户端提交的版本号>=服务器上取出来(可能是从Db,也可能是从缓存)的版本号,那么也是可以的
        if (jwtVerOfReq >= user.JWTVersion)
        {
            await next();
        }
        else
        {
            var result = new ObjectResult($"JWTVersion mismatch");
            result.StatusCode = (int)HttpStatusCode.Unauthorized;
            context.Result = result;
            return;
        }
    }
}
  1. 注册
services.Configure<MvcOptions>(opt=>{
    opt.Filters.Add<JWTValidationFilter>();
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

步、步、为营

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值