You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6 Web API JWT认证异常:配置Bearer Token仍返回401未授权

解决ASP.NET Core 6 JWT认证返回401且报MissingMethodException的问题

问题核心

你遇到的MissingMethodException: 找不到Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration方法错误,本质是JWT相关NuGet包版本不匹配导致的。这个方法属于特定版本的Microsoft.IdentityModel.Tokens包,当生成Token和验证Token的包版本不一致,或者ASP.NET Core认证组件与IdentityModel组件版本不兼容时,就会出现这个缺失方法的情况,进而导致Token验证失败返回401。

解决步骤

1. 统一JWT相关NuGet包版本

打开项目的NuGet包管理器(或直接编辑.csproj文件),确保以下包的版本完全一致,且与ASP.NET Core 6的版本匹配(推荐使用6.x系列版本,比如6.25.0):

  • Microsoft.AspNetCore.Authentication.JwtBearer
  • Microsoft.IdentityModel.Tokens
  • System.IdentityModel.Tokens.Jwt

如果使用.csproj编辑,示例配置如下:

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.25" />
  <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.25.0" />
  <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.25.0" />
</ItemGroup>

2. 清理并重建项目

执行以下命令彻底清理并还原依赖:

dotnet clean
dotnet restore
dotnet build

3. 验证Token生成与认证配置的一致性

确保Token生成逻辑中的参数,和Program.cs里的JWT认证参数完全一致:

  • 生成Token时的Issuer、Audience必须和认证配置中的ValidIssuer、ValidAudience完全相同
  • 签名密钥SigningKey必须完全一致,且密钥长度符合算法要求(比如HS256算法要求密钥至少16字节,即32个字符的字符串)

示例认证配置(Program.cs):

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

// 必须保证管道顺序:先认证,再授权
app.UseAuthentication();
app.UseAuthorization();

示例Token生成逻辑:

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
    issuer: _configuration["Jwt:Issuer"],
    audience: _configuration["Jwt:Audience"],
    expires: DateTime.UtcNow.AddMinutes(30),
    signingCredentials: creds);

return new JwtSecurityTokenHandler().WriteToken(token);

4. 检查间接依赖的包冲突

如果上述步骤无效,用以下命令查看所有依赖包的版本,找出是否有其他包间接引入了旧版本的IdentityModel组件:

dotnet list package

若发现冲突,可在.csproj中添加PackageReference强制指定统一版本:

<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.25.0" PrivateAssets="all" />

内容的提问来源于stack exchange,提问作者Kyle Angelo Gonzales

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:23:33