0
votes

I am implementing Windows authentication on an ASP.NET Core 2.2 server application, and everything is working fine except SignalR in Angular 8 app. The error I am receiving is the following one:

Access to XMLHttpRequest at 'http://localhost:2110/api/aircrafts/hub/negotiate' from origin 'http://localhost:2302' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

localhost:2302 is the client part running Angular 8 with @aspnet/[email protected] and localhost:2110 is the server part. Here is my server code:

Startup.cs Configure Method

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

Startup.cs ConfigureServices method

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

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

webSettings.AllowedHosts contains localhost:2302.

launchsettings.json:

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

And this is the Angular code:

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

where url is localhost:2110/api/aircrafts/hub

Any help would be greatly appreciated.

1

1 Answers

3
votes

First of all, you should not use the package @aspnet/[email protected] because it is abandoned and migrated by microsoft to the package @microsoft/signalr and it is already on version 3.1.0, as you can see in this documentation.

About CORS, you should configure your CORS like:

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