使用 SIGNAL R 的 angular 7 和 ASP.NET core 2.2 的 CORS 策略问题

CORS policy issue with angular 7 and ASP.NET core 2.2 using SIGNAL R

我和我的朋友 运行 遇到 API 和 angular 客户端的 CORS 问题。 我们正在尝试建立一个 link,我们正在使用 signalR 并且客户端(Angular 7)注册自己以接收来自服务器(ASP .NET core 2.2)的消息。

在浏览器控制台中,我收到此消息:

Access to XMLHttpRequest at 'https://ourEndpoint/CoordinatorHub/negotiate' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

服务器端

我们的startup.cs是这样的,我们已经关注了微软文档

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddDbContext<OneRoomContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("OneRoomContext")));
    services.AddSignalR();
    // Register the Swagger services
    services.AddSwaggerDocument();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDeveloperExceptionPage();
    app.UseCors(builder =>
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials());
    //if (env.IsDevelopment())
    //{
    //    app.UseDeveloperExceptionPage();
    //    app.UseCors(builder =>
    //        builder.AllowAnyOrigin()
    //               .AllowAnyMethod()
    //               .AllowAnyHeader());
    //}
    //else
    //{
    //    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    //    app.UseHsts();
    //}
    app.UseSignalR(route =>
    {
        route.MapHub<CoordinatorHub>("/CoordinatorHub");
    });
    app.UseHttpsRedirection();
    app.UseMvc();
    // Register the Swagger generator and the Swagger UI middlewares
    app.UseSwagger();
    app.UseSwaggerUi3();
}

这是我们的控制器:

using Microsoft.AspNetCore.SignalR;
using oneroom_api.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace oneroom_api.SignalR
{
    public class CoordinatorHub : Hub
    {
        public Task SendNewUser(User user)
        {
            return Clients.All.SendAsync("GetNewUser", user);
        }
    }
}

Azure 门户:允许 CORS * 来源

客户端

这就是我们的 app.component.ts 的样子 (ngOnInit)

我们正在使用@aspnet/signalr包

this.hubConnection = new signalR.HubConnectionBuilder()
    .withUrl(localStorage.getItem('endpoint') + '/CoordinatorHub')
    .build();

this.hubConnection.on('send', data => {
  console.log(data);
});

this.hubConnection.start().then(() => this.hubConnection.invoke('send', 'Hello'));

如何禁用凭据模式或我需要在哪里提供 withCredentials 状态?

谢谢你的时间和答案

如错误消息所述,您需要明确指定允许的 CORS 来源。

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

您当然可以尝试让 SignalR 停止发出要求您的 API 发送 Access-Control-Allow-Credentials header 的请求,具体取决于您打算如何处理身份验证(cookie 或不记名令牌?)。这比简单地扩展 "allowed origin" 列表要复杂得多。除此之外,您真的应该避免对来源使用通配符,尤其是在生产系统上。

对于本地开发,将开发服务器的地址添加到允许的来源列表中就足够了。必须为您希望应用程序可访问的每个地址扩展该列表。

 app.UseCors(builder =>
    builder.WithOrigins("http://localhost:4200")
           .AllowAnyMethod()
           .AllowAnyHeader()
           .AllowCredentials());

除了代码更改之外,您还必须从 Azure 应用服务配置中删除通配符 CORS 条目。否则更改将无效,因为 CORS header 会被 Azure 覆盖。

基本上问题是 Azure 上的 CORS 覆盖了我们 startup.cs 中的代码,我们最终删除了 Azure 门户上的配置 CORS,一切正常。由于旧的 signalR-client 已被弃用,我们使用了带有 angular 的 signal R npm 包。