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

RLo*_*ris 5 cors signalr asp.net-core angular

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

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

已从CORS策略阻止从原点' http:// localhost:4200 ' 在' https:// ourEndpoint / CoordinatorHub / negotiate ' 访问XMLHttpRequest :对预检请求的响应未通过访问控制检查:'当请求的凭据模式为“ include”时,响应中的“ Access-Control-Allow-Origin”标头不得为通配符“ *”。XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。

服务器端

我们的startup.cs看起来像这样,我们已经关注了microsoft docs

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();
}
Run Code Online (Sandbox Code Playgroud)

这是我们的控制器:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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'));
Run Code Online (Sandbox Code Playgroud)

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

谢谢您的时间和答复

Red*_*one 6

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

当请求的凭据模式为“ include”时,响应中“ Access-Control-Allow-Origin”标头的值不得为通配符“ *”。

当然,您可以尝试使SignalR停止发出要求API发送Access-Control-Allow-Credentials标头的请求,具体取决于您打算如何处理身份验证(cookie或承载令牌?)。这比单纯扩展“允许的来源”列表要复杂得多。除此之外,您真的应该避免使用通配符作为源,尤其是在生产系统上。

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

 app.UseCors(builder =>
    builder.WithOrigins("http://localhost:4200")
           .AllowAnyMethod()
           .AllowAnyHeader()
           .AllowCredentials());
Run Code Online (Sandbox Code Playgroud)

除了代码更改之外,还必须从Azure App Service配置中删除通配符CORS条目。否则,更改将无效,因为CORS标头将被Azure覆盖。

  • 我们在代码中使用了AnyOrigin(),它似乎可以正常工作。实际上,我们的配置与上面的配置几乎相同 (2认同)

RLo*_*ris 1

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