You need to enable JavaScript to run this app. ASP.NET Core 基于DI与Identity实现JWT令牌吊销校验的迁移问题
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 基于DI与Identity实现JWT令牌吊销校验的迁移问题

自定义JWT校验器的依赖注入实现方案

核心问题根因

你当前代码中直接通过new CustomJwtValidator()的方式添加校验器,导致自定义校验器完全脱离了ASP.NET Core的依赖注入容器生命周期,自然无法拿到构造函数中注册的CustomUserManager、CustomDbContext等服务。
下面提供两种可直接落地的实现方案,可完全复刻旧系统的令牌吊销校验逻辑:

方案一:通过JwtBearer事件钩子实现自定义校验(推荐)

这是ASP.NET Core官方推荐的实现路径,不需要完全重写JWT令牌的校验逻辑,复用默认的签名、签发方、受众校验能力,只在基础校验通过后插入令牌吊销状态的校验逻辑,服务获取通过请求级依赖注入完成,无生命周期冲突问题。
具体操作:

  • 保留原有TokenValidationParameters的全量配置,不需要清空默认的SecurityTokenValidators,删除原有手动new自定义校验器的代码。
  • 在AddJwtBearer配置中添加OnTokenValidated事件钩子,直接从请求上下文中解析需要的服务。

代码实现:

public void ConfigureServices(IServiceCollection services)
{
   // 原有DbContext、Identity注册逻辑保持不变
   services.AddDbContext<CustomDbContext>(options => options.UseMySql(Configuration.GetConnectionString("ConnectionString")));
   services.AddIdentity<CustomUser, CustomRole>()
           .AddUserManager<CustomUserManager>();

   services.AddAuthentication()
            .AddJwtBearer(options =>
            {
                // 原有TokenValidationParameters配置保持不变
                options.RequireHttpsMetadata = true;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ClockSkew = TimeSpan.FromMinutes(1),
                    ValidIssuer = Configuration["JwtSettings:Issuer"],
                    ValidAudience = Configuration["JwtSettings:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSettings:SigningKey"])),
                };

                // 插入自定义吊销校验逻辑
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = async context =>
                    {
                        // 从请求服务容器中拿到已注册的CustomUserManager
                        var userManager = context.HttpContext.RequestServices.GetRequiredService<CustomUserManager>();
                        var userId = context.Principal.GetUserId();
                        // 从令牌声明中提取jti
                        var jti = context.Principal.FindFirstValue(JwtRegisteredClaimNames.Jti);

                        // 查询当前用户的所有有效令牌
                        var userTokens = await userManager.GetTokensAsync(userId, JwtConstants.TokenType);
                        // 校验当前令牌的jti是否在有效列表中
                        if (!userTokens.Any(x => x.Name == jti))
                        {
                            context.Fail("令牌已被吊销");
                        }
                    }
                };
            });
}

这种实现的优势:

  • 完全复用成熟的默认JWT校验逻辑,不需要重复实现令牌解码、签名校验等通用能力,减少自定义代码的bug风险。
  • 服务生命周期与请求绑定,CustomUserManager、CustomDbContext均为Scoped生命周期,与请求级容器完全匹配,不会出现数据库上下文提前释放、跨请求数据污染的问题。

方案二:依赖注入注册自定义SecurityTokenValidator

如果需要保留自定义SecurityTokenValidator的实现,只需要调整注册方式,不要直接在配置委托中实例化校验器,通过DI工厂从请求容器中解析实例即可。
具体操作:

  • 给CustomJwtValidator添加构造函数注入,在构造函数中声明需要的服务依赖。
public class CustomJwtValidator : ISecurityTokenValidator
{
    private readonly CustomUserManager _userManager;
    // 构造函数通过DI注入依赖
    public CustomJwtValidator(CustomUserManager userManager)
    {
        _userManager = userManager;
    }

    public ClaimsPrincipal? ValidateToken(string token, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
    {
        // 复用默认JWT校验器完成基础校验
        var defaultHandler = new JwtSecurityTokenHandler();
        var principal = defaultHandler.ValidateToken(token, validationParameters, out validatedToken);
        
        // 插入令牌存在性校验逻辑
        var userId = principal.GetUserId();
        var jti = principal.FindFirstValue(JwtRegisteredClaimNames.Jti);
        var userTokens = _userManager.GetTokensAsync(userId, JwtConstants.TokenType).GetAwaiter().GetResult();
        if (!userTokens.Any(x => x.Name == jti))
        {
            throw new SecurityTokenValidationException("令牌已被吊销");
        }

        return principal;
    }

    // 实现ISecurityTokenValidator接口要求的其他成员
    public bool CanValidateToken => true;
    public int MaximumTokenSizeInBytes { get; set; } = TokenValidationParameters.DefaultMaximumTokenSizeInBytes;
    public bool CanReadToken(string securityToken) => true;
}
  • 在服务注册阶段将CustomJwtValidator按Scoped生命周期加入DI容器,通过工厂机制完成实例获取:
public void ConfigureServices(IServiceCollection services)
{
   // 原有DbContext、Identity注册逻辑保持不变
   services.AddDbContext<CustomDbContext>(options => options.UseMySql(Configuration.GetConnectionString("ConnectionString")));
   services.AddIdentity<CustomUser, CustomRole>()
           .AddUserManager<CustomUserManager>();
   // 将自定义校验器注册到DI容器
   services.AddScoped<CustomJwtValidator>();

   services.AddAuthentication()
            .AddJwtBearer(options =>
            {
                // 原有TokenValidationParameters配置保持不变
                options.RequireHttpsMetadata = true;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ClockSkew = TimeSpan.FromMinutes(1),
                    ValidIssuer = Configuration["JwtSettings:Issuer"],
                    ValidAudience = Configuration["JwtSettings:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSettings:SigningKey"])),
                };

                options.SecurityTokenValidators.Clear();
                // 通过工厂从请求容器中解析自定义校验器实例,不要直接new
                options.SecurityTokenValidators.Add(
                    serviceProvider => serviceProvider.GetRequiredService<CustomJwtValidator>()
                );
            });
}

注意:JwtBearer的校验器注册接口本身支持传入工厂委托获取实例,直接在配置委托中new出来的对象完全脱离DI容器,构造函数中的依赖不会被自动赋值,自然无法获取CustomUserManager等服务。

常见踩坑点

  • 不要把Scoped生命周期的CustomUserManager、CustomDbContext提升为单例,否则会出现数据库上下文被提前释放、跨请求数据污染的异常。
  • 令牌吊销校验逻辑要放在基础签名、签发方校验通过之后执行,避免恶意构造的无效令牌触发不必要的数据库查询。
  • 因为JWT本身不设置过期时间,需要配合Identity的令牌生命周期设置,在用户登出、主动吊销时及时删除对应的令牌记录,避免令牌长期有效。

内容的提问来源于stack exchange,提问作者LightAndrek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.15 08:24:03