使用SIGNAL R

时间:2019-02-21 13:59:55

标签: angular asp.net-core cors signalr

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

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

  

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

服务器端

我们的startup.cs看起来像这样,我们已经关注了Microsoft文档

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状态?

谢谢您的时间和答复

2 个答案:

答案 0 :(得分:3)

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

  

当请求的凭据模式为“包括”时,响应中“ <访问控制-允许-起源”标头的值不得为通配符“ *”。

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

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

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

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

答案 1 :(得分:0)

基本上,问题在于azure上的CORS覆盖了startup.cs中的代码,我们最终删除了azure门户上的配置CORS,一切正常。由于不赞成使用旧的signalR-client,因此我们一直使用带有角度的signal R npm软件包。