首页 > 解决方案 > 身份验证更新后的 WEBAPI CORS 错误

问题描述

我有一个在 Azure 中运行的 Angular 应用程序,它连接到我也在 Azure 中运行的 WEBAPI。分开的网站。一切正常,但最近在我的 API 代码中,我开始收到此警告:

Severity    Code    Description Project File    Line    Suppression State
Warning CS0618  'AzureADAuthenticationBuilderExtensions.AddAzureAD(AuthenticationBuilder, Action<AzureADOptions>)' is obsolete: 'This is obsolete and will be removed in a future version. Use AddMicrosoftWebApiAuthentication from Microsoft.Identity.Web instead. See https://aka.ms/ms-identity-web.'   MExBrightsign.API   D:\Repos\WHQMuseums\MExBrightsign\CMS\MExBrightsign.API\Startup.cs  53  Active

目前我的 startup.cs 文件中有以下内容:

    services
        .AddAuthentication("Azure")
        .AddPolicyScheme("Azure", "Authorize AzureAd or AzureAdBearer", options =>
        {
            options.ForwardDefaultSelector = context =>
            {
                var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
                if (authHeader?.StartsWith("Bearer") == true)
                {
                    return JwtBearerDefaults.AuthenticationScheme;
                }
                return AzureADDefaults.AuthenticationScheme;
            };
        })
        .AddJwtBearer(opt =>
        {
            opt.Audience = Configuration["AAD:ResourceId"];
            opt.Authority = $"{Configuration["AAD:Instance"]}{Configuration["AAD:TenantId"]}";
        })
        .AddAzureAD(options => Configuration.Bind("AzureAd", options));

如果我改变这一行: .AddAzureAD(options => Configuration.Bind("AzureAd", options));

到 .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));

我在 Angular 应用程序的所有调用中都收到了 CORS 错误。

没有其他任何改变。

我还需要做什么才能避免出现 CORS 错误。现在,我只是离开过时的电话,但我想在电话被删除之前找到解决方案。

谢谢你的帮助。

编辑:附加信息 Jason Pan 的评论对我没有帮助,但它确实让我思考。我已经配置了 Azure 应用服务 CORS。我意识到我从未真正部署到 Azure 并看到了 CORS 错误。我在本地运行。我做了 1 行更改,对 WEBAPI 的所有 Angular 调用都返回了 CORS 错误。请注意,我的 WEBAPI 的 startup.cs 文件中有以下内容:

    var origins = Configuration.GetSection("AppSettings:AllowedOrigins").Value.Split(",");
    services.AddCors(o => o.AddPolicy(mexSpecificOrigins, builder =>
    {
        builder.WithOrigins(origins)
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials()
               .SetIsOriginAllowed((host) => true);
    }));

这是 appsettings.json:

  "AppSettings": {
    "EnvironmentName": "LOCAL",
    "AllowedOrigins": "http://localhost:4200"
  },

所以,我在本地运行时,只在 startup.cs 中配置了 CORS,但在 Azure 中,我在 startup.cs 和 Azure CORS 配置中都有。

困扰我的是我只更改了 1 行。与新电话有什么区别。我认为它增加了额外的安全性。我将尝试部署到 Azure,并查看 CORS 错误是否继续存在。如果这行得通,那么我只需要担心当地的发展。

标签: azure-active-directorycorsazure-web-app-serviceasp.net-core-webapimicrosoft-identity-platform

解决方案


添加到 startup.cs 的配置方法(在 app.UseRouting() 之后):

  app.UseCors(mexSpecificOrigins);

并将您的起源更改为:

var origins = Configuration["AppSettings:AllowedOrigins"];

或更改 AllowedOrigins:

"AllowedOrigins": ["http://localhost:4200"]

并尝试删除:

 .SetIsOriginAllowed((host) => true);

推荐阅读