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

已生成JWT但无法访问授权接口,报错无认证处理器注册

JWT认证报错解决方案

问题根源

报错No authentication handlers are registered的核心原因是:未在项目中正确注册JWT Bearer认证处理器,或者认证/授权中间件的调用顺序错误。

分步修复

1. 修正Startup.cs的认证服务配置

在ConfigureServices方法中,必须明确添加JWT Bearer处理器,并指定默认认证方案:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

public void ConfigureServices(IServiceCollection services)
{
    // 读取appsettings中的JWT配置
    var jwtSettings = Configuration.GetSection("JWTConfig").Get<JWTConfig>();

    // 注册认证服务
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = jwtSettings.Issuer,
            ValidAudience = jwtSettings.Audience,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))
        };
    });

    // 注册授权服务
    services.AddAuthorization();

    // 其他服务配置
    services.AddControllers();
}

2. 确保中间件调用顺序正确

在Configure方法中,UseAuthentication必须在UseAuthorization之前执行,否则认证逻辑不会生效:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();
    app.UseRouting();

    // 先认证,后授权
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

3. 验证JWT配置与生成逻辑一致性

  • appsettings.json配置示例:
{
  "JWTConfig": {
    "SecretKey": "your_secure_secret_key_min_16_chars",
    "Issuer": "your_app_issuer",
    "Audience": "your_app_audience",
    "ExpiresInMinutes": 60
  }
}
  • Token生成代码需匹配配置:
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(jwtSettings.SecretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "test_user") }),
    Expires = DateTime.UtcNow.AddMinutes(jwtSettings.ExpiresInMinutes),
    Issuer = jwtSettings.Issuer,
    Audience = jwtSettings.Audience,
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);

4. 请求格式验证

调用接口时,必须在请求头中携带正确的授权信息:

Authorization: Bearer {your_generated_token}

额外排查点

  • 确认项目已安装Microsoft.AspNetCore.Authentication.JwtBearer NuGet包
  • 检查SecretKey长度不小于16字符(HmacSha256算法要求)
  • 验证生成的Token内容,确保Issuer、Audience与认证配置完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:22:55