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

Blazor WASM托管应用添加AddMicrosoftIdentityWebApp后触发CORS拦截问题

问题解决方法

问题根源

你两次调用AddAuthentication导致默认认证方案被覆盖,最后一次设置的OpenIdConnectDefaults.AuthenticationScheme(用于服务器端登录)成为全局默认,而API控制器需要的是JWT Bearer认证。当未认证的API请求进来时,系统会触发OpenIdConnect的重定向逻辑,跳转到微软登录页,这个跨域请求因为对方服务器没有配置允许https://localhost:5001的CORS规则,所以被浏览器拦截。

修复步骤

  1. 合并认证配置,指定默认方案
    不要分开调用AddAuthentication,而是在同一个配置块中添加两种认证方案,同时明确API的默认认证方案为JwtBearer。修改后的配置代码如下:

    var builder = WebApplication.CreateBuilder(args);
    
    // 合并认证配置,设置JwtBearer为默认API认证方案
    builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        // 为服务器端登录页面单独指定OpenIdConnect方案
        options.DefaultSignInScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
    
  2. 配置CORS策略(可选但推荐)
    为API添加CORS策略,允许客户端的源访问:

    // 添加CORS服务
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("BlazorClientPolicy", policy =>
        {
            policy.WithOrigins("https://localhost:5001") // 替换为你的客户端实际地址
                  .AllowAnyHeader()
                  .AllowAnyMethod();
        });
    });
    
    // 在中间件中启用CORS,注意要放在UseRouting之后,UseAuthentication之前
    var app = builder.Build();
    app.UseCors("BlazorClientPolicy");
    
  3. 为API控制器指定认证方案(可选)
    如果某些API需要明确使用JWT认证,可以在控制器或Action上添加:

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public class WeatherForecastController : ControllerBase
    {
        // ...
    }
    

验证

修改后重启服务,客户端调用API时会使用JWT Bearer认证,不会触发重定向到登录页,CORS错误即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 08:30:37