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

ASP.NET Core Identity同时支持Razor Pages与MAUI认证配置问题

同时支持ASP.NET Core Identity Web认证与MAUI Token认证的正确配置

问题1:混合两种认证方式是否可行?

完全可行。ASP.NET Core原生支持多认证方案共存,只需正确配置认证服务、授权策略和中间件,就能同时满足Razor Pages/MVC的Cookie认证(带自动登录跳转)和MAUI客户端的Bearer Token认证需求。

正确配置步骤

1. 服务注册配置

替换你现有的Identity和认证配置为以下代码:

// 配置Identity核心服务,包含角色、EF存储、默认UI和Token提供者
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultUI()
    .AddDefaultTokenProviders()
    .AddApiEndpoints(); // 启用Identity API端点支持

// 配置多认证方案:Cookie(Web应用) + Bearer(API/MAUI)
builder.Services.AddAuthentication(options =>
{
    // 设置默认认证/挑战/登录方案为Cookie,保证Web应用未登录时自动跳转登录页
    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ApplicationScheme;
})
// 注册Bearer Token认证处理程序,对应Identity.Bearer方案
.AddBearerToken(IdentityConstants.BearerScheme);

// 保留全局授权策略,强制所有请求需认证
builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();

    // 可选:添加专门针对API的授权策略,强制使用Bearer认证
    options.AddPolicy("ApiBearer", policy =>
    {
        policy.AddAuthenticationSchemes(IdentityConstants.BearerScheme);
        policy.RequireAuthenticatedUser();
    });
});

2. 中间件与端点配置

确保中间件顺序正确,并映射Identity API和Web路由:

var app = builder.Build();

// 常规中间件(静态文件、异常处理等)
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

// 认证中间件必须在授权中间件之前
app.UseAuthentication();
app.UseAuthorization();

// 映射Identity API端点,可选择应用ApiBearer策略
app.MapIdentityApi<ApplicationUser>()
    .RequireAuthorization("ApiBearer");

// 映射Razor Pages路由(MVC项目替换为MapControllerRoute)
app.MapRazorPages();

app.Run();

之前配置的问题分析

  1. 第一种配置(AddIdentityApiEndpoints):
    AddIdentityApiEndpoints会默认将全局默认认证/挑战方案设置为Bearer,导致Web应用未登录时,系统尝试用Bearer方案挑战而非Cookie,因此不会自动跳转到登录页。手动指定默认方案为Cookie即可解决。

  2. 第二种配置(AddIdentity + AddApiEndpoints):
    仅调用AddApiEndpoints启用了Identity API,但未注册Bearer Token的认证处理程序,所以调用API时找不到Identity.Bearer对应的处理逻辑,抛出异常。添加AddBearerToken(IdentityConstants.BearerScheme)即可注册该处理程序。

额外注意事项

  • 原有WebAPI接口兼容:如果你的现有JS调用的WebAPI需要同时支持Cookie和Bearer认证,可以在控制器/端点上指定双认证方案:
    [Authorize(AuthenticationSchemes = $"{IdentityConstants.ApplicationScheme},{IdentityConstants.BearerScheme}")]
    public class MyExistingApiController : ControllerBase
    {
        // 接口逻辑
    }
    
  • 中间件顺序:UseAuthentication必须在UseAuthorization之前,且都要在路由中间件(UseRouting)之后、端点映射之前。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:14:50