angular - 使用 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();
其中url是localhost:2110/api/aircrafts/hub
任何帮助将不胜感激。
解决方案
首先,您不应该使用该软件包@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));
});
推荐阅读
- visual-studio - 无法在 Visual Studio 中为终端设置电力线字体
- tkinter - 从函数更改 tkinter bg
- lambda - 如何在 lambda 演算中减少 beta?
- tsql - TSQL:当 Scehma 更改时删除临时表会出错
- flutter - 里弗波德 | 真正需要多少个提供者才能只观察一个类的一个状态
- bash - 用于将一个大文件拆分为多个文件的 Unix 脚本,每个文件中有两对标签,每个文件都有一个文件名的命名约定
- python - 使用整数列表无法让 If-Statement 在 Jinja 中正确工作
- javascript - 上次修改时间戳
- css - 渲染页面时如何禁用动画?
- r - 嵌套模块和 ObserveEvents - R Shiny