首页 > 解决方案 > 使用 Windows 身份验证时 SignalR 客户端 CORS 错误

问题描述

我正在 ASP.NET Core 2.2 服务器应用程序上实现 Windows 身份验证,除了 Angular 8 应用程序中的 SignalR 之外,一切都运行良好。我收到的错误如下:

从源“ http://localhost:2302 ”访问“ http://localhost:2110/api/aircrafts/hub/negotiate ”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

localhost:2302是使用@aspnet/signalr@1.1.4运行Angular 8的客户端部分,而localhost:2110是服务器部分。这是我的服务器代码:

Startup.cs 配置方法

app.UseCors("CORS");
app.UseAuthentication();
var relativeUri = webSettings.SignalRAircraftsUri.ToString();
app.UseSignalR(hubs => { hubs.MapHub<AircraftsHub>(relativeUri); });

Startup.cs 配置服务方法

services.AddCors(options =>
        {
            options.AddPolicy("CORS", builder =>
            {
                builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithOrigins(webSettings.AllowedHosts.ToArray())
                    .AllowCredentials();
            });
        });

        services.AddSignalR();
        services.AddAuthentication(IISDefaults.AuthenticationScheme);

webSettings.AllowedHosts包含localhost:2302

启动设置.json:

  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:2110",
      "sslPort": 0
    }
  },

这是 Angular 代码:

const signalRConnection = new signalR.HubConnectionBuilder().withUrl(url).build();
signalRConnection.start();

其中urllocalhost:2110/api/aircrafts/hub

任何帮助将不胜感激。

标签: angularauthenticationcorssignalr

解决方案


首先,您不应该使用该软件包@aspnet/signalr@1.1.4,因为它已被 microsoft 放弃并迁移到该软件包 @microsoft/signalr,并且它已经在版本3.1.0中,正如您在本文档中看到的那样。

关于 CORS,您应该像这样配置 CORS:

services.AddCors(options =>
{
    options.AddPolicy(CorsPolicy, builder => builder.WithOrigins(webSettings.AllowedHosts.ToArray())
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials()
        .SetIsOriginAllowed((host) => true));
});

推荐阅读