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

ASP.NET Core 8中Identity Bearer令牌授权返回401未授权问题

问题分析与解决方案

你遇到的核心问题是**AddIdentityApiEndpoints 与手动配置的 JwtBearer 认证中间件冲突**,导致登录返回的令牌无法被自定义JWT验证逻辑识别,最终触发401未授权。

问题根源

AddIdentityApiEndpoints<IdentityUser> 是ASP.NET Core 8内置的快捷认证API,它已经封装了完整的令牌生成、验证流程——使用ASP.NET Core的Data Protection加密系统生成令牌,而非传统的签名JWT。你手动添加的AddJwtBearer配置期望验证标准JWT,但登录接口返回的是Data Protection加密令牌,两者不兼容,自然无法通过验证。

解决方案:移除多余的JWT配置

直接删除Program.cs中手动添加的AddAuthentication和AddJwtBearer相关代码即可,AddIdentityApiEndpoints已帮你处理所有认证逻辑。

修改后的Program.cs核心代码:

public class Program
{
     public static void Main(string[] args)
     {
         var builder = WebApplication.CreateBuilder(args);

         // 保留IdentityApiEndpoints配置,无需额外JWT设置
         builder.Services.AddIdentityApiEndpoints<IdentityUser>(options =>
         {
             options.Password.RequiredLength = 6;
             options.Password.RequireNonAlphanumeric = false;
             options.Password.RequireDigit = false;
             options.Password.RequireUppercase = false;
             options.Password.RequireLowercase = false;
         })
             .AddEntityFrameworkStores<MM_DbContext>();

         // 其他服务配置保持不变
         builder.Services
             .AddScoped<Services.IArmouryService, Services.TestArmouryService>()
             .AddScoped<Services.IBattleboardService, Services.TestBattleboardService>()
             .AddScoped<Services.ICharacterService, Services.TestCharacterService>()
             .AddScoped<Services.IKingdomService, Services.TestKingdomService>()
             .AddScoped<Services.ISoupkitchenService, Services.TestSoupkitchenService>()
             .AddScoped<Services.ITreasuryService, Services.TestTreasuryService>();

         builder.Services.AddDbContext<MM_DbContext>(options =>
             options.UseNpgsql(builder.Configuration.GetConnectionString("Db")));

         builder.Services.AddControllers().AddNewtonsoftJson(o => { });

         builder.Services.AddEndpointsApiExplorer();
         builder.Services.AddSwaggerGen();

         var app = builder.Build();

         app.MapIdentityApi<IdentityUser>();

         if (app.Environment.IsDevelopment())
         {
             app.UseSwagger();
             app.UseSwaggerUI();
         }

         // 确保中间件顺序正确:先认证,再授权
         app.UseAuthentication();
         app.UseAuthorization();
         app.MapControllers();

         app.Run();
     }
}

额外调试建议

如果修改后仍有问题,可启用详细日志定位具体失败原因:
在appsettings.Development.json中添加日志配置:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore.Authentication": "Debug"
    }
  }
}

运行程序后查看控制台输出的认证相关日志,即可明确令牌验证失败的具体细节。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:49:50