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

ASP.NET Core 7.0混合MVC/Web API应用微软身份平台双认证配置求助

解决ASP.NET Core 7同时配置MVC交互式认证与Web API非交互式认证的问题

问题核心在于你将全局默认认证方案设为OpenIdConnectDefaults.AuthenticationScheme,导致所有请求(包括API)都会优先尝试交互式认证,触发登录重定向。以下是可行的修复方案:

1. 调整认证服务配置,明确两种认证方案

取消全局默认认证方案的指定,分别配置Web API的JWT Bearer认证和MVC的OpenID Connect认证,同时确保Cookie认证的方案名明确(MVC交互式认证依赖Cookie存储身份):

var builder = WebApplication.CreateBuilder(args);

// 不指定全局默认认证方案,后续通过授权策略区分使用场景
var authenticationBuilder = builder.Services.AddAuthentication();

// 配置Web API的JWT Bearer认证
authenticationBuilder.AddMicrosoftIdentityWebApi(
    builder.Configuration.GetSection("AzureAd"),
    JwtBearerDefaults.AuthenticationScheme);

// 配置MVC的OpenID Connect认证,同时指定Cookie认证方案
authenticationBuilder.AddMicrosoftIdentityWebApp(
    builder.Configuration.GetSection("AzureAd"),
    OpenIdConnectDefaults.AuthenticationScheme,
    CookieAuthenticationDefaults.AuthenticationScheme);

builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

2. 创建专属授权策略,区分MVC与API场景

为两类端点分别创建授权策略,明确指定对应的认证方案:

builder.Services.AddAuthorization(options =>
{
    // API专属策略:仅接受JWT Bearer认证
    options.AddPolicy("ApiPolicy", policy =>
    {
        policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
        policy.RequireAuthenticatedUser();
    });

    // MVC专属策略:使用OpenID Connect+Cookie认证
    options.AddPolicy("MvcPolicy", policy =>
    {
        policy.AuthenticationSchemes.Add(OpenIdConnectDefaults.AuthenticationScheme);
        policy.AuthenticationSchemes.Add(CookieAuthenticationDefaults.AuthenticationScheme);
        policy.RequireAuthenticatedUser();
    });
});

3. 配置JWT认证事件,禁止重定向返回401

默认情况下,认证失败可能触发重定向,需要在JWT配置中覆盖挑战事件,直接返回401响应:

authenticationBuilder.AddMicrosoftIdentityWebApi(
    builder.Configuration.GetSection("AzureAd"),
    JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearerOptions(options =>
    {
        options.Events = new JwtBearerEvents
        {
            OnChallenge = context =>
            {
                // 终止默认重定向逻辑
                context.HandleResponse();
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                context.Response.ContentType = "application/json";
                return context.Response.WriteAsync("{\"error\": \"未授权访问\"}");
            }
        };
    });

4. 绑定策略到对应端点

可以通过两种方式绑定策略:

  • 控制器特性绑定:在MVC控制器上标注[Authorize(Policy = "MvcPolicy")],API控制器上标注[Authorize(Policy = "ApiPolicy")]
  • 路由全局绑定:在Program.cs的路由配置中直接为分支指定策略,无需逐个控制器加特性:
// API路由绑定ApiPolicy
app.MapControllers()
    .RequireAuthorization("ApiPolicy");

// MVC默认路由绑定MvcPolicy
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}")
    .RequireAuthorization("MvcPolicy");

app.UseAuthentication();
app.UseAuthorization();

这样配置后,MVC端点会走交互式认证流程,API端点会验证JWT令牌,认证失败时返回401而非重定向。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:15:04