【问题标题】:CORS in asp.net core 2.1 and angularasp.net core 2.1 和 angular 中的 CORS
【发布时间】:2019-10-17 19:55:58
【问题描述】:

关于这个主题有很多讨论,但没有一个对我有用。我有一个带有 Angular 7 应用程序的 asp.net core api 2.1。

错误:

"fleet:1 访问 XMLHttpRequest at 'https://localhost:44354/api/test' 来自原点'http://localhost:4200' 已被 CORS 策略阻止:没有“访问控制允许来源” 请求的资源上存在标头。”

启动:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

    services.AddCors((options =>
    {
        options.AddPolicy("AzurePolicy", builder => builder
                    .WithOrigins("http://localhost:4200", "https://localhost:4200", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials()
         );
    }));

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors("AzurePolicy");
    app.UseAuthentication();

    app.UseMvc();
}

配置:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "xx.com",
    "TenantId": "xx",
    "ClientId": "xx"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

我什至在控制器中添加了以下内容:

 [EnableCors("AllowSpecificOrigin")]

你可以在这里做更多的事情吗?

【问题讨论】:

  • 您的“AzurePolicy”策略在哪里定义? app.UseCors("AzurePolicy");?
  • 您需要了解您在做什么(cors 是什么以及它是如何工作的)例如允许任何来源与允许凭证不兼容,如果您正在开发这种系统,您真的应该知道为什么.
  • @juan 我试图关注这篇文章。 adrianszen.com/2019/02/19/… 你必须从某个地方开始。您有解决方案的建议吗?
  • @Juan 我尝试删除 AllowCredentials 然后得到 401。如果您有任何意见,我们将不胜感激。
  • 401 表示您缺少身份验证,因为不允许凭据,cookie 或身份验证标头都不会发送到服务器。问题是您不能将这些发送到允许任何来源的服务器。您需要将源锁定到您的特定 url 以允许凭据。这不是您在路上会发现的唯一东西,从这里开始,它将帮助您解决任何问题:developer.mozilla.org/en-US/docs/Web/HTTP/CORS

标签: angular asp.net-core


【解决方案1】:

appsettings.json中添加AzureActiveDirectory设置

像这样:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com",
  "Domain": "AD_DOMAIN",
  "TenantId": "TENANT_GUID",
  "ClientId": "APPLICATIONID_GUID"
}

更多详情请关注Article

【讨论】:

  • 有点好笑,正是我使用的那篇文章。我有描述的配置文件。你在这里添加什么? services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddAzureADBearer(options => Configuration.Bind("SHOULDNT THIS BE NAME OF CONFIG. That is AzureAd", options))?同样适用于你在那里添加什么字符串? options.AddPolicy("ALSO AzureAd?")?
猜你喜欢
  • 2019-08-29
  • 2021-07-25
  • 2021-01-26
  • 2019-08-22
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
相关资源
最近更新 更多