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

ASP.NET Core Minimal API配置Identity Bearer Scheme实现JWT认证时登录报错的问题求助

ASP.NET Core Minimal API配置Identity Bearer Scheme实现JWT认证时登录报错的问题求助

嗨,我刚踩过一模一样的坑,给你捋清楚怎么解决:

你遇到的这个报错No sign-in authentication handlers are registered,本质是因为你用了Identity的登录逻辑(不管是默认端点还是自定义的),但Identity缺少对应的Bearer Token认证处理程序——也就是你查到的AddBearerToken方法,它的作用就是注册这个处理程序,让Identity能生成并处理JWT Token。

第一步:先装必要的NuGet包

首先得确保你安装了Microsoft.AspNetCore.Identity.BearerToken这个包,AddBearerToken方法就在这个包里,没装的话会找不到这个方法。

第二步:修改你的Program.cs代码

我结合你的现有代码,给你改出完整可运行的版本,关键部分我标出来:

using Backend.Entities;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// 先添加你的DbContext(假设你用EF Core,记得替换成你自己的DbContext)
// builder.Services.AddDbContext<YourDbContext>(options =>
//     options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 配置Identity服务,指定你的用户实体
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<YourDbContext>() // 替换成你的DbContext
    .AddDefaultTokenProviders();

// 👇这就是解决报错的核心!添加Bearer Token支持,和Identity关联
builder.Services.AddBearerToken(IdentityConstants.BearerScheme, options =>
{
    // 配置Token有效期,比如1小时
    options.TokenLifetime = TimeSpan.FromHours(1);
    // 这里的签名密钥、Issuer、Audience要和下面JwtBearer的配置完全一致
    var jwtSettings = builder.Configuration.GetSection("Jwt");
    options.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Key"]));
    options.TokenValidationParameters.ValidIssuer = jwtSettings["Issuer"];
    options.TokenValidationParameters.ValidAudience = jwtSettings["Audience"];
});

// 配置JWT Bearer认证,用于后续验证Token
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    var jwtSettings = builder.Configuration.GetSection("Jwt");
    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["Key"]))
    };
});

// 添加授权服务
builder.Services.AddAuthorization();

// 其他Minimal API服务配置
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// 开发环境启用Swagger
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

// 注意中间件顺序:先认证,再授权!
app.UseAuthentication();
app.UseAuthorization();

// 👇如果用Identity的默认登录端点,加上这个就能自动生成/login等端点
app.MapIdentityApi<ApplicationUser>();

// 这里可以添加你自己的API端点
// app.MapGet("/api/protected", () => "Hello from protected endpoint")
//    .RequireAuthorization();

app.Run();

第三步:补充appsettings.json的JWT配置

在你的appsettings.json里加上JWT的关键配置:

{
  "Jwt": {
    "Key": "YourSuperSecretKeyHereNeedsToBeAtLeast16Chars",
    "Issuer": "YourAppName",
    "Audience": "YourAppClient"
  },
  "ConnectionStrings": {
    "DefaultConnection": "YourDatabaseConnectionString"
  }
}

关键知识点解释

  • AddBearerToken(IdentityConstants.BearerScheme):这个方法就是给Identity注册了Bearer Token的登录处理程序,完美解决你遇到的报错。
  • 必须保证AddBearerToken和AddJwtBearer的签名密钥、Issuer、Audience一致,这样生成的Token才能被正确验证。
  • 如果用MapIdentityApi<ApplicationUser>(),Identity会自动帮你生成登录、注册、刷新Token等端点,不用自己写登录逻辑,非常方便。

按照上面的步骤改完,你再试登录应该就不会报错了!

备注:内容来源于stack exchange,提问作者codeouz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 13:29:31