前军教程网

中小站长与DIV+CSS网页布局开发技术人员的首选CSS学习平台

8.3JWT提前撤回 提前撤退



8.3JWT提前撤回

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

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

实现步骤:

  1. 1. 为实体类User增加一个long类型的属性JWTVersion
  2. 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. 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 = #34;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(#34;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(#34;JWTVersion mismatch");
            result.StatusCode = (int)HttpStatusCode.Unauthorized;
            context.Result = result;
            return;
        }
    }
}
  1. 1. 注册
services.Configure<MvcOptions>(opt=>{
    opt.Filters.Add<JWTValidationFilter>();
})
```---
title: 8.3JWT提前撤回
toc: true
cover: /img/cover/85.svg
thumbnail: /img/25.svg
date: 2024-05-08 19:07:11
tags: .net core
categories: .net core
excerpt: 8.3JWT提前撤回

---

## 8.3JWT提前撤回

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

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

实现步骤:

1. 为实体类User增加一个long类型的属性JWTVersion
2. 修改产生JWT的代码,实现JWTVersion自增

```csharp
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. 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 = #34;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(#34;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(#34;JWTVersion mismatch");
            result.StatusCode = (int)HttpStatusCode.Unauthorized;
            context.Result = result;
            return;
        }
    }
}
  1. 1. 注册
services.Configure<MvcOptions>(opt=>{
    opt.Filters.Add<JWTValidationFilter>();
})

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言