Aspnetcore: CORS issue with latest SignalR with CORS and MVC with default routes

Created on 9 Nov 2018  ·  37Comments  ·  Source: dotnet/aspnetcore

Hello,

I'm on the latest version of SignalR Core and using this with Asp.Net Core, using CORS and MVC: On HttpSysServer for server and Angular 4 for client.

I used to have everything running perfectly (system is in production), but I refactored how my routes are defined. I set them up now using UseMvcWithDefaultRoute. As soon as I switched to this, I got an error message enabling my SignalR connection. If I switch back to only UseMvc, the connection occurs correctly.

Below I'll include the relevant code and error message.

I'm wondering what I don't have correctly configured, but also why a preflight is sent to a websocket request? (Unless it's falling back on another protocol?)

Thanks!

public void ConfigureServices(IServiceCollection services)
{

            //...

            #region  Setup CORS

            var corsBuilder = new CorsPolicyBuilder();


            //corsBuilder.AllowAnyOrigin(); // For anyone access.
            corsBuilder.WithOrigins(new[] { "http://localhost:4200",
                                            "http://productionSite.com" }); // for a specific url. Don't add a forward slash on the end!
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowCredentials();
            corsBuilder.AllowAnyMethod();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });

            #endregion

            services.AddSignalR(options =>
            {
                options.EnableDetailedErrors = true;
            });

            services.AddMvc(config =>
            {

                // Add XML Content Negotiation
                config.RespectBrowserAcceptHeader = true;
                config.InputFormatters.Add(new XmlSerializerInputFormatter());
                config.OutputFormatters.Add(new XmlSerializerOutputFormatter());

                // Global exception handler
                config.Filters.Add(typeof(Filters.GlobalExceptionFilterAttribute));

            });

            // ...

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceScopeFactory scopeFactory, IApplicationLifetime applicationLifetime)
        {

            // ...

            app.UseCors("SiteCorsPolicy"); // UseCors() has to be called before UseMvcWithDefaultRoute() and before UseSignalR()

            app.UseSignalR(routes =>
            {
                routes.MapHub<MainHub>("/MainHub");
            }); // UseSignalR() has to be called after UseCors()

            app.UseMvcWithDefaultRoute(); // UseMvcWithDefaultRoute() has to be called after UseCors()

            // app.UseMvc(); // UseMvcWithDefaultRoute() has to be called after UseCors()

            // app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); 

            // ...

});
        }

And error message from the client connecting.

`Access to XMLHttpRequest at 'http://serverUrl/v1/AppName/MainHub/negotiate' from origin 'http://localhost:4200' 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.

Utils.js:193 Warning: Error from HTTP request. 0:

ConsoleLogger.log @ Utils.js:193
xhr.onerror @ HttpClient.js:98
wrapFn @ zone.js:1166
ZoneDelegate.invokeTask @ zone.js:425
onInvokeTask @ core.es5.js:3881
ZoneDelegate.invokeTask @ zone.js:424
Zone.runTask @ zone.js:192
ZoneTask.invokeTask @ zone.js:499
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
error (async)
customScheduleGlobal @ zone.js:1666
ZoneDelegate.scheduleTask @ zone.js:411
onScheduleTask @ zone.js:301
ZoneDelegate.scheduleTask @ zone.js:405
Zone.scheduleTask @ zone.js:236
Zone.scheduleEventTask @ zone.js:262
(anonymous) @ zone.js:1832
(anonymous) @ http.es5.js:1274
Observable._trySubscribe @ Observable.js:172
Observable.subscribe @ Observable.js:160
(anonymous) @ datasvc.ts:28
ZoneAwarePromise @ zone.js:890
DataSvc.makeRequest @ datasvc.ts:27
BorrowService.getAll@ borrow.service.ts:73
BorrowGridComponent.initializeData @ borrow-grid.component.ts:236
BorrowGridComponent.ngOnInit @ borrow-grid.component.ts:101
checkAndUpdateDirectiveInline @ core.es5.js:10843
checkAndUpdateNodeInline @ core.es5.js:12341
checkAndUpdateNode @ core.es5.js:12284
debugCheckAndUpdateNode @ core.es5.js:13141
debugCheckDirectivesFn @ core.es5.js:13082
(anonymous) @ BorrowPage.html:23
debugUpdateDirectives @ core.es5.js:13067
checkAndUpdateView @ core.es5.js:12251
callViewAction @ core.es5.js:12599
execComponentViewsAction @ core.es5.js:12531
checkAndUpdateView @ core.es5.js:12257
callViewAction @ core.es5.js:12599
execEmbeddedViewsAction @ core.es5.js:12557
checkAndUpdateView @ core.es5.js:12252
callViewAction @ core.es5.js:12599
execComponentViewsAction @ core.es5.js:12531
checkAndUpdateView @ core.es5.js:12257
callWithDebugContext @ core.es5.js:13467
debugCheckAndUpdateView @ core.es5.js:13007
ViewRef_.detectChanges @ core.es5.js:10174
(anonymous) @ core.es5.js:4812
ApplicationRef_.tick @ core.es5.js:4812
(anonymous) @ core.es5.js:4684
ZoneDelegate.invoke @ zone.js:392
onInvoke @ core.es5.js:3890
ZoneDelegate.invoke @ zone.js:391
Zone.run @ zone.js:142
NgZone.run @ core.es5.js:3821
next @ core.es5.js:4684
schedulerFn @ core.es5.js:3635
SafeSubscriber.__tryOrUnsub @ Subscriber.js:239
SafeSubscriber.next @ Subscriber.js:186
Subscriber._next @ Subscriber.js:127
Subscriber.next @ Subscriber.js:91
Subject.next @ Subject.js:56
EventEmitter.emit @ core.es5.js:3621
checkStable @ core.es5.js:3855
onHasTask @ core.es5.js:3903
ZoneDelegate.hasTask @ zone.js:445
ZoneDelegate._updateTaskCount @ zone.js:465
Zone._updateTaskCount @ zone.js:289
Zone.runTask @ zone.js:209
drainMicroTaskQueue @ zone.js:602
Promise.then (async)
scheduleMicroTask @ zone.js:585
ZoneDelegate.scheduleTask @ zone.js:414
Zone.scheduleTask @ zone.js:236
Zone.scheduleMicroTask @ zone.js:256
scheduleResolveOrReject @ zone.js:871
ZoneAwarePromise.then @ zone.js:981
PlatformRef_._bootstrapModuleWithZone @ core.es5.js:4537
PlatformRef_.bootstrapModule @ core.es5.js:4522
(anonymous) @ main.ts:11
./src/main.ts @ main.bundle.js:1135
__webpack_require__ @ inline.bundle.js:55
0 @ main.bundle.js:1143
__webpack_require__ @ inline.bundle.js:55
webpackJsonpCallback @ inline.bundle.js:26
(anonymous) @ main.bundle.js:1
Utils.js:190 Error: Failed to complete negotiation with the server: Error
ConsoleLogger.log @ Utils.js:190
(anonymous) @ HttpConnection.js:230
step @ HttpConnection.js:33
(anonymous) @ HttpConnection.js:14
rejected @ HttpConnection.js:6
ZoneDelegate.invoke @ zone.js:392
onInvoke @ core.es5.js:3890
ZoneDelegate.invoke @ zone.js:391
Zone.run @ zone.js:142
(anonymous) @ zone.js:873
ZoneDelegate.invokeTask @ zone.js:425
onInvokeTask @ core.es5.js:3881
ZoneDelegate.invokeTask @ zone.js:424
Zone.runTask @ zone.js:192
drainMicroTaskQueue @ zone.js:602
ZoneTask.invokeTask @ zone.js:503
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
error (async)
customScheduleGlobal @ zone.js:1666
ZoneDelegate.scheduleTask @ zone.js:411
onScheduleTask @ zone.js:301
ZoneDelegate.scheduleTask @ zone.js:405
Zone.scheduleTask @ zone.js:236
Zone.scheduleEventTask @ zone.js:262
(anonymous) @ zone.js:1832
(anonymous) @ http.es5.js:1274
Observable._trySubscribe @ Observable.js:172
Observable.subscribe @ Observable.js:160
(anonymous) @ datasvc.ts:28
ZoneAwarePromise @ zone.js:890
DataSvc.makeRequest @ datasvc.ts:27
BorrowService.getAll@ borrow.service.ts:73
BorrowGridComponent.initializeData @ borrow-grid.component.ts:236
BorrowGridComponent.ngOnInit @ borrow-grid.component.ts:101
checkAndUpdateDirectiveInline @ core.es5.js:10843
checkAndUpdateNodeInline @ core.es5.js:12341
checkAndUpdateNode @ core.es5.js:12284
debugCheckAndUpdateNode @ core.es5.js:13141
debugCheckDirectivesFn @ core.es5.js:13082
(anonymous) @ BorrowPage.html:23
debugUpdateDirectives @ core.es5.js:13067
checkAndUpdateView @ core.es5.js:12251
callViewAction @ core.es5.js:12599
execComponentViewsAction @ core.es5.js:12531
checkAndUpdateView @ core.es5.js:12257
callViewAction @ core.es5.js:12599
execEmbeddedViewsAction @ core.es5.js:12557
checkAndUpdateView @ core.es5.js:12252
callViewAction @ core.es5.js:12599
execComponentViewsAction @ core.es5.js:12531
checkAndUpdateView @ core.es5.js:12257
callWithDebugContext @ core.es5.js:13467
debugCheckAndUpdateView @ core.es5.js:13007
ViewRef_.detectChanges @ core.es5.js:10174
(anonymous) @ core.es5.js:4812
ApplicationRef_.tick @ core.es5.js:4812
(anonymous) @ core.es5.js:4684
ZoneDelegate.invoke @ zone.js:392
onInvoke @ core.es5.js:3890
ZoneDelegate.invoke @ zone.js:391
Zone.run @ zone.js:142
NgZone.run @ core.es5.js:3821
next @ core.es5.js:4684
schedulerFn @ core.es5.js:3635
SafeSubscriber.__tryOrUnsub @ Subscriber.js:239
SafeSubscriber.next @ Subscriber.js:186
Subscriber._next @ Subscriber.js:127
Subscriber.next @ Subscriber.js:91
Subject.next @ Subject.js:56
EventEmitter.emit @ core.es5.js:3621
checkStable @ core.es5.js:3855
onHasTask @ core.es5.js:3903
ZoneDelegate.hasTask @ zone.js:445
ZoneDelegate._updateTaskCount @ zone.js:465
Zone._updateTaskCount @ zone.js:289
Zone.runTask @ zone.js:209
drainMicroTaskQueue @ zone.js:602
Promise.then (async)
scheduleMicroTask @ zone.js:585
ZoneDelegate.scheduleTask @ zone.js:414
Zone.scheduleTask @ zone.js:236
Zone.scheduleMicroTask @ zone.js:256
scheduleResolveOrReject @ zone.js:871
ZoneAwarePromise.then @ zone.js:981
PlatformRef_._bootstrapModuleWithZone @ core.es5.js:4537
PlatformRef_.bootstrapModule @ core.es5.js:4522
(anonymous) @ main.ts:11
./src/main.ts @ main.bundle.js:1135
__webpack_require__ @ inline.bundle.js:55
0 @ main.bundle.js:1143
__webpack_require__ @ inline.bundle.js:55
webpackJsonpCallback @ inline.bundle.js:26
(anonymous) @ main.bundle.js:1
Utils.js:190 Error: Failed to start the connection: Error
ConsoleLogger.log @ Utils.js:190
(anonymous) @ HttpConnection.js:191
step @ HttpConnection.js:33
(anonymous) @ HttpConnection.js:14
rejected @ HttpConnection.js:6
ZoneDelegate.invoke @ zone.js:392
onInvoke @ core.es5.js:3890
ZoneDelegate.invoke @ zone.js:391
Zone.run @ zone.js:142
(anonymous) @ zone.js:873
ZoneDelegate.invokeTask @ zone.js:425
onInvokeTask @ core.es5.js:3881
ZoneDelegate.invokeTask @ zone.js:424
Zone.runTask @ zone.js:192
drainMicroTaskQueue @ zone.js:602
ZoneTask.invokeTask @ zone.js:503
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
error (async)
customScheduleGlobal @ zone.js:1666
ZoneDelegate.scheduleTask @ zone.js:411
onScheduleTask @ zone.js:301
ZoneDelegate.scheduleTask @ zone.js:405
Zone.scheduleTask @ zone.js:236
Zone.scheduleEventTask @ zone.js:262
(anonymous) @ zone.js:1832
(anonymous) @ http.es5.js:1274
Observable._trySubscribe @ Observable.js:172
Observable.subscribe @ Observable.js:160
(anonymous) @ datasvc.ts:28
ZoneAwarePromise @ zone.js:890
DataSvc.makeRequest @ datasvc.ts:27
BorrowService.getAll@ borrow.service.ts:73
BorrowGridComponent.initializeData @ borrow-grid.component.ts:236
BorrowGridComponent.ngOnInit @ borrow-grid.component.ts:101
checkAndUpdateDirectiveInline @ core.es5.js:10843
checkAndUpdateNodeInline @ core.es5.js:12341
checkAndUpdateNode @ core.es5.js:12284
debugCheckAndUpdateNode @ core.es5.js:13141
debugCheckDirectivesFn @ core.es5.js:13082
(anonymous) @ BorrowPage.html:23
debugUpdateDirectives @ core.es5.js:13067
checkAndUpdateView @ core.es5.js:12251
callViewAction @ core.es5.js:12599
execComponentViewsAction @ core.es5.js:12531
checkAndUpdateView @ core.es5.js:12257
callViewAction @ core.es5.js:12599
execEmbeddedViewsAction @ core.es5.js:12557
checkAndUpdateView @ core.es5.js:12252
callViewAction @ core.es5.js:12599
execComponentViewsAction @ core.es5.js:12531
checkAndUpdateView @ core.es5.js:12257
callWithDebugContext @ core.es5.js:13467
debugCheckAndUpdateView @ core.es5.js:13007
ViewRef_.detectChanges @ core.es5.js:10174
(anonymous) @ core.es5.js:4812
ApplicationRef_.tick @ core.es5.js:4812
(anonymous) @ core.es5.js:4684
ZoneDelegate.invoke @ zone.js:392
onInvoke @ core.es5.js:3890
ZoneDelegate.invoke @ zone.js:391
Zone.run @ zone.js:142
NgZone.run @ core.es5.js:3821
next @ core.es5.js:4684
schedulerFn @ core.es5.js:3635
SafeSubscriber.__tryOrUnsub @ Subscriber.js:239
SafeSubscriber.next @ Subscriber.js:186
Subscriber._next @ Subscriber.js:127
Subscriber.next @ Subscriber.js:91
Subject.next @ Subject.js:56
EventEmitter.emit @ core.es5.js:3621
checkStable @ core.es5.js:3855
onHasTask @ core.es5.js:3903
ZoneDelegate.hasTask @ zone.js:445
ZoneDelegate._updateTaskCount @ zone.js:465
Zone._updateTaskCount @ zone.js:289
Zone.runTask @ zone.js:209
drainMicroTaskQueue @ zone.js:602
Promise.then (async)
scheduleMicroTask @ zone.js:585
ZoneDelegate.scheduleTask @ zone.js:414
Zone.scheduleTask @ zone.js:236
Zone.scheduleMicroTask @ zone.js:256
scheduleResolveOrReject @ zone.js:871
ZoneAwarePromise.then @ zone.js:981
PlatformRef_._bootstrapModuleWithZone @ core.es5.js:4537
PlatformRef_.bootstrapModule @ core.es5.js:4522
(anonymous) @ main.ts:11
./src/main.ts @ main.bundle.js:1135
__webpack_require__ @ inline.bundle.js:55
0 @ main.bundle.js:1143
__webpack_require__ @ inline.bundle.js:55
webpackJsonpCallback @ inline.bundle.js:26
(anonymous) @ main.bundle.js:1
signalr.service.ts:53 Error while establishing connection
signalr.service.ts:54 Error
at new HttpError (Errors.js:25)
at XMLHttpRequest.xhr.onerror [as __zone_symbol__ON_PROPERTYerror] (HttpClient.js:99)
at XMLHttpRequest.wrapFn (zone.js:1166)
at ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.invokeTask (zone.js:424)
at Zone.runTask (zone.js:192)
at ZoneTask.invokeTask [as invoke] (zone.js:499)
at invokeTask (zone.js:1540)
at XMLHttpRequest.globalZoneAwareCallback (zone.js:1566)`

area-mvc question

All 37 comments

@sebastienricher what version of ASP.NET Core \ SignalR are you on? Browsers normalize the Origin header when making a preflight request. This means the Origin header would appear as http://productionsite.com (note the casing) and the CORS middleware will ignore the request. We tweaked some of this in 2.2, so the version would affect further investigation.

Hi @pranavkm, I'm on AspNetCore v2.0.1 / MVC v2.0.0,

I've updated everything to the latest (core v2.1.6 and mvc v2.1.3) and I still get the same behavior.

image

And SignalR is on 1.0.4

@sebastienricher the change is in the 2.2. release which hasn't been released as yet. Regardless, could you change the log level in your application to the most verbose level and see what the CORS middleware has to say? Usually it'll indicate why it decided to not provide a CORS response.

@pranavkm Where can I set this configuration, I tried changing the log level for my application but I don't see any logs about CORS replies. I ran with "Verbose" and "Debug" as LogLevel.

I'm currently running this locally so my Angular client is on http://localhost:4200 and my server application is on http://some-url/ using a local DNS entry. Note that I do have a dash in the url.

I know the "order" of things is important, I'm currently setup as CORS --> SignalR --> MVC. I did try to switch things around CORS --> MVC --> SignalR but it did not help the situation.

Edit: I tried running with the v2.2.0-preview3-35497 version just in case, did not work.

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2#default-minimum-level
Is it possible to capture a fiddler trace? Or browser network trace? https://github.com/aspnet/SignalR/wiki/Diagnostics-Guide#network-traces

Also, try 2.2.0-rtm-35688 version of CORS as some of the preview3 builds had a bug.

The order shouldn't matter as long as the CORS middleware appears first. When I run the server with logging enabled, here's a snippet of what I see:

info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[5]
      CORS policy execution failed.
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[6]
      Request origin http://localhost:9001 does not have permission to access the resource.

Do none of these appear in your server logs?

Hi. We're closing this issue as no response or updates have been provided in a timely manner and we have been unable to reproduce it. If you have more details and are encountering this issue please add a new reply and re-open the issue.

Hi folks,

Sorry for the delayed response, had other work priorities. Got some time this morning (just as the issue was being closed haha), here is a Fiddler log for the "MainHub" endpoint for SignalR. I'm not too familiar with Fiddler to don't hesitate to ask for specifics.

Request headers:

OPTIONS /v1/XYZ/MainHub/negotiate HTTP/1.1
Host: lb-services
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
DNT: 1
Access-Control-Request-Headers: x-requested-with
Accept: /
Accept-Encoding: gzip, deflate
Accept-Language: en-CA,en;q=0.9,fr;q=0.8

As opposed to a working "non-sockets" call:

GET /v1/XYZ/api/core/GetAllCounterparties HTTP/1.1
Host: lb-services
Connection: keep-alive
Accept: application/json, text/plain, /
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
DNT: 1
Referer: http://localhost:4200/borrows
Accept-Encoding: gzip, deflate
Accept-Language: en-CA,en;q=0.9,fr;q=0.8


And for the response headers:

HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Server: Microsoft-IIS/10.0
Public: OPTIONS, TRACE, GET, HEAD, POST
X-Powered-By: ASP.NET
Date: Mon, 03 Dec 2018 20:53:53 GMT
Content-Length: 0

As opposed to a working "non-sockets" call:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Vary: Origin
Server: Microsoft-HTTPAPI/2.0
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Allow-Credentials: true
Date: Mon, 03 Dec 2018 20:53:54 GMT


Otherwise I'm still working on getting more log details, I got the log level to be very detailed, example:

{"Timestamp":"2018-12-03T15:50:31.8513011-05:00","Level":"Information","MessageTemplate":"CORS policy execution successful.","RenderedMessage":"CORS policy execution successful.","Properties":{"EventId":{"Id":4},"SourceContext":"Microsoft.AspNetCore.Cors.Infrastructure.CorsService","RequestId":"XXXXXX","RequestPath":"/borrow/GetDirections","CorrelationId":null}}

But I cannot find any logs for my MainHub SignalR endpoint. Still working on that but wanted to provide more details.

I'll also update to the suggested version, will post updates soon.

(Also, I'm looking for that re-open button?)

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2#default-minimum-level
Is it possible to capture a fiddler trace? Or browser network trace? https://github.com/aspnet/SignalR/wiki/Diagnostics-Guide#network-traces

Also, try 2.2.0-rtm-35688 version of CORS as some of the preview3 builds had a bug.

How can I set my project to 2.2.0-rtm-35688? I'm on 2.2.0-preview3-35497 (Latest prerelease) and I'm not sure how to set the version higher than that? Thanks!

--> Update: On tried 2.2.0-rtm-35688, setting this in my .csproj file. Ran the solution, got the same behavior in terms of the SignalR connection failing with the CORS message. Still working on getting Hubs in the logs.

@pranavkm when you have some time, could you take a look please?

@pranavkm can you take a peek at this? Thanks!

Any update to fix this problem?

A complete nightmare. The equivalent project in ASP.NET Core 2.1 works perfect. In 2.2:

_Response to preflight request doesn't pass access control check:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

Is there a way to solve without having to use hard code? Like

services.AddCors(options => { options.AddPolicy(allowSpecificOrigins, builder => { builder.WithOrigins("http://localhost:50768") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); });
In other words.
What happens if I know the destination (client ip) after publishing the application ?, that is, could I add a WithOrigin dynamically? –

Hei, guys! Anybody found a solution to this problem? Or shall I just revert the project to .NET Core 2.1?

You could specify the origin in your WithOrigin call. The changes from 2.1 to 2.2 were, essentially, to comply with details in the CORS specification, which make your apps more secure. Apologies to @harveytriana for this causing additional complexity.

Hi @bradygaster, not sure why this has become close as my original issue is still not solved. I've not tackled this issue recently since other work priorities. But I intend to try again with 2.2. Has no one tried to reproduce this?

It isn't something we need to try, it's that the CORS middleware evolved from 2.1 to 2.2, becoming more secure yet also more restrictive in usage. You'd can't have, effectively, "allow everything," so we'll need to triage and get you guidance if specifying an origin is too restrictive.

@bradygaster I'm looking back at my initial post, my CORS policy is:

corsBuilder.WithOrigins(new[] { "http://localhost:4200",
"http://productionSite.com" }); // for a specific url. Don't add a forward slash on the end!
corsBuilder.AllowAnyHeader();
corsBuilder.AllowCredentials();
corsBuilder.AllowAnyMethod();

So I am not allowing any origin, but rather setting my dev and production urls. Is there an adjustment to that configuration that is needed?

Thanks for the help!

What you have here mirrors a the settings for a demo project on which I'm working ATM. The code for that is below, and for that site, SignalR and REST APIs both work from clients in the origin list.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(_corsPolicyName,
        builder =>
        {
            builder.WithOrigins(
                    "https://localhost:5001", 
                    "https://localhost:4001",
                    "https://localhost:44307",
                    "https://localhost:44394"
                )
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
        });
    });

    services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors(_corsPolicyName);
    app.UseRouting();
    app.UseDefaultFiles();
    app.UseStaticFiles();
}

And are you using "UseMvcWithDefaultRoute" ?

How to fix this problem? AllowCredentials didn't help

In my case adding allow credentials AllowCredentials did the trick.

ConfigureServices

services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
                builder
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                .WithOrigins("http://localhost:4200");
            }));

services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Configure

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
    routes.MapHub<NotifyHub>("/notify");
});

app.UseMvc();

Hi,
I'm experiencing the same problem and this is my startup.cs code:

under ConfigureServices()

    services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                    builder =>
                    {
                        builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();
                    });
            });
            services.AddSignalR();

Configure

          app.UseCors("CorsPolicy");
            app.UseSignalR(routes =>
            {

                routes.MapHub<StronglyTypedScaleHub>("/hubpages/strongscalehub");
                routes.MapHub<HubLibrary.Hubs.ScaleHub>("/ScaleHub");
            });

            app.UseMvcWithDefaultRoute();

Is the issue because I didn't provide specific origins?

Edit; I have also tried specifying the origin and I still get the same error

            services.AddCors(options =>
            {
                options.AddPolicy("LocalPolicy",
                    builder =>
                    {
                        builder
                        .WithOrigins("http://localhost:53465")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();
                    });
            });

The error:

_Response to preflight request doesn't pass access control check:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

And on Edge Browser


HTTP405: BAD METHOD - The HTTP verb used is not supported.
(XHR)OPTIONS - http://localhost:54325/ScaleHub/negotiate

Yes, you should explicitly add the list of allowed origins, * is no longer acceptable.

Yes, you should explicitly add the list of allowed origins, * is no longer acceptable.

@shahabganji , I have tried that and I still get the error. Am I implementing it wrongly?
Ahh, just realised I mispelled the policy! So sorry!

The name of policy in your app.UseCores do not Mach the name of the policy you have defined, in this case “AllowAll”

On Jun 15, 2019, at 17:51, captmomo notifications@github.com wrote:

Yes, you should explicitly add the list of allowed origins, * is no longer acceptable.
@shahabganji , I have tried that and I still get the error. Am I implementing it wrongly?


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or mute the thread.

Thank you Saeed!
Yes I realised that. Using the right name and specifying the origin address
in the CORS policy rectified the error.
Thanks again.

On Sat, 15 Jun 2019 at 9:35 PM, Saeed Ganji notifications@github.com
wrote:

The name of policy in your app.UseCores do not Mach the name of the policy
you have defined, in this case “AllowAll”

On Jun 15, 2019, at 17:51, captmomo notifications@github.com wrote:

Yes, you should explicitly add the list of allowed origins, * is no
longer acceptable.
@shahabganji , I have tried that and I still get the error. Am I
implementing it wrongly?


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or mute the thread.


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/aspnet/AspNetCore/issues/5385?email_source=notifications&email_token=AGDEEVS3GD5AZHWBO3DBIM3P2TV2XA5CNFSM4GK33FGKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODXYYJVY#issuecomment-502367447,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AGDEEVUJPL5DSNQ274RLDBTP2TV2XANCNFSM4GK33FGA
.

@sebastienricher did your original issue get resolved?

I'm unfortunately busy with other parts of the project, but I do intend to
revisit, as I will need to tackle this sooner or later, from what I read
here, I'm thinking this should work. I'll head back into this probably in
august after vacations.

On Wed, Jul 3, 2019 at 1:07 PM Artak notifications@github.com wrote:

@sebastienricher https://github.com/sebastienricher did your original
issue got resolved?


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/aspnet/AspNetCore/issues/5385?email_source=notifications&email_token=ABOQZEXDPRLTXLO6LUL2F5TP5TMDJA5CNFSM4GK33FGKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODZFC2JY#issuecomment-508177703,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABOQZEVG26GTKKUIZHL562TP5TMDJANCNFSM4GK33FGA
.

--

Sébastien Richer

Mobile : 514-296-0130

I'm having the same issue with ASP.NET Core 3 Preview 8 and "@microsoft/signalr": "^3.0.0-preview8.19405.7",

Access to XMLHttpRequest at 'http://10.10.10.10/myhub/negotiate' from origin 'http://localhost:8080' 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.

        public void ConfigureServices(IServiceCollection services)
        {
            // ********************
            // Setup CORS
            // ********************
            services.AddCors(options =>
            {
                options.AddPolicy(_corsPolicyName, builder => builder
                    .WithOrigins(
                        "http://localhost:8080",
                        "https://localhost:8080",
                        "http://localhost:4200",
                        "https://localhost:4200")
                    .AllowAnyMethod()
                    .AllowAnyHeader());
            });

            services.AddControllers();
            services.AddSignalR();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSerilogRequestLogging();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseCors(_corsPolicyName);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<MyHub>("/myhub");
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.RoutePrefix = string.Empty;
            });
        }

You need .AllowCredentials() as part of your CORS setup.

After adding .AllowCredentials() I get a different error.

Access to XMLHttpRequest at 'http://10.10.10.10/mysvc/myhub/negotiate' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

I moved app.UseCors(_corsPolicyName); above app.UseRouting(); as shown below and I'm now getting connected. Is there any plans to make the order irrelevant?

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(_corsPolicyName);

            app.UseSerilogRequestLogging();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<MyHub>("/myhub");
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.RoutePrefix = string.Empty;
            });
        }

Is there any plans to make the order irrelevant?

Middleware are supposed to follow the order they are written in. We will not be changing that.

I can confirm,
that I've faced same issue on .NET core 2.2 and SignalR where source of trouble was incorrect order of Middlewares. I think in this thread we are mixing this issue and issue call ".AllowCredentials() always".

This Middleware order worked for me:
//UseSignalR must be before UseMvc!!! app.UseSignalR(routes => { routes.MapHub<ChatHub>("/chatHub"); }); app.UseMvcWithDefaultRoute();

I would consider this issue closed.

@dalibor-sanzeru is right that various issues have been conflated here.

CORS functionality is now more inline with spec and the docs need to acknowledge this where appropriate. That and use of credentials is necessary and is currently a requirement for SignalR. There has also been some rumblings on whether to make it configurable and whether or not it would be possible.

Please file a new issue for any further discussions or questions about CORS and SignalR. Thanks!

Was this page helpful?
0 / 5 - 0 ratings