Skip to content
This repository has been archived by the owner on Dec 18, 2018. It is now read-only.

SignalR Javascript client CORS issue 'Access-Control-Allow-Origin' header in the response must not be the wildcard #2095

Closed
davenewza opened this issue Apr 19, 2018 · 55 comments
Labels
status: Investigate Investigation item
Milestone

Comments

@davenewza
Copy link

davenewza commented Apr 19, 2018

I are unable to connect to our SignalR hub, hosted on Azure App Service, using the JavaScript client found here: https://docs.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-2.1

Failed to load https://myapp.azurewebsites.net/location/negotiate: 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'. Origin 'null' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Startup.cs looks something like this:

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
        {
            builder
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowAnyOrigin()
                .AllowCredentials();
        }));

        services
            .AddMvcCore()
            .AddJsonFormatters();

        services.AddSignalR();

        var provider = services.BuildServiceProvider();
        return provider;
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors("CorsPolicy");

        app.UseMvc();

        app.UseSignalR(routes =>
        {
            routes.MapHub<LocationsHub>("/location");
        });
    }

I am using the latest 2.1.0-preview2-final libraries.

Allowed origins is set to "*" in the Web App and websockets are enabled:

image

I am able to connect just fine to this hub using the C# client.

@davenewza
Copy link
Author

davenewza commented Apr 19, 2018

I have set the Allowed Origins in the Azure Web App to http://localhost:12345

image

And specifying the origin in Startup.cs:

services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
    builder
        .AllowAnyMethod()
        .AllowAnyHeader()
        .WithOrigins("http://localhost:12345")
        .DisallowCredentials();
}));

And now the error:

Failed to load https://myapp.azurewebsites.net/location/negotiate: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.

image

@analogrelay
Copy link
Contributor

I think it might be because you have both the ASP.NET Core CORS feature and the Azure Web Apps CORS feature, and I think you probably haven't properly specified all the configuration options in the Azure one. Can you try removing all the settings from the Azure portal's CORS settings and try again? The fact that the response headers don't include Server: Kestrel makes me think that you're getting a response directly from the Azure Websites front-end and it's never reaching the application (The X-Powered-By: ASP.NET is provided by IIS too, so it doesn't indicate that the request is reaching the app either).

If that doesn't fix it, let me know and we can keep digging.

@analogrelay analogrelay added the status: Investigate Investigation item label Apr 19, 2018
@analogrelay
Copy link
Contributor

analogrelay commented Apr 19, 2018

+@HaoK who's done some verification of SignalR and CORS.

@HaoK
Copy link
Member

HaoK commented Apr 19, 2018

I'll take a look as well

@davenewza as a reference point, I got Cors working without Azure in the picture a few days ago using preview 2 bits with https://github.com/HaoK/Random/tree/master/SignalRStuff/CorsServer and https://github.com/HaoK/Random/tree/master/SignalRStuff/CorsClient

@davenewza
Copy link
Author

davenewza commented Apr 20, 2018

@anurse I have deleted all settings from the Azure Web App CORS configuration and have reverted to my initial CORS configuration in Startup.cs (allow everything).

Now getting a 204 from the negotiate endpoint! And it appears to be delivered from Kestrel as well.

But this error still comes up in Chrome:

Failed to load https://myapp.azurewebsites.net/location/negotiate: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.

image

@analogrelay
Copy link
Contributor

Can you post your complete Startup.cs? It's very hard to tell from the snippets you have if things are ordered correctly, and some of your snippets have had conflicting CORS configurations.

@Maciejszuchta
Copy link

I'm experiencing the same issue.

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

And in my angular client app, which is hosted on localhost:4200

I do:

`const hubConnectuion = new HubConnection("http://localhost:54496/signalr");

hubConnectuion
  .start()
  .then(() => console.log('Connection started!'))
  .catch(err => console.log('Error while establishing connection'));`

And I'm still getting

image

@Maciejszuchta
Copy link

Maciejszuchta commented Apr 24, 2018

Ok looks like moving Cors configuration to Configure method in Startup.cs solved the problem:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader().AllowAnyMethod().AllowCredentials();
});
app.UseSignalR(routes => routes.MapHub("/signalr"));
}

@analogrelay
Copy link
Contributor

analogrelay commented Apr 25, 2018

@Maciejszuchta In your earlier code, were you referencing the named policy CorsPolicy in your UseCors call? CORS allows you to configure multiple named policies, as well as an unnamed "default" policy. .UseCors() only applies the default policy. If you use services.AddCors(o => o.AddPolicy("Name", builder => ...)) you have to make sure you reference that policy in the middleware: app.UseCors("Name")

@davenewza are you still encountering this issue? We haven't had any update from you since my earlier request for your Startup.cs code.

@davenewza
Copy link
Author

@anurse I can confirm that it is working now. I assumed that it was due to an update to the package on NPM, but I see there hasn't been a new version. We did remove all CORS settings from the Web App's configuration and our startup looks something as follows:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

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

        services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCookiePolicy();
        app.UseCors("CorsPolicy");
        app.UseSignalR(routes =>
        {
            routes.MapHub<DevicesHub>("/device");
        });
    }
}

@analogrelay
Copy link
Contributor

analogrelay commented May 4, 2018

Ok, sounds like maybe the Azure Web App CORS settings were conflicting with the ones in ASP.NET Core.

@pieperu
Copy link

pieperu commented May 13, 2018

I was experiencing the same issue after upgrading my server to the latest

<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.0-rc1-final" />

due to having to upgrade my client package to

"@aspnet/signalr": "1.0.0-rc1-update1"

I can also confirm that removing all settings from the CORS section of my Azure API Service resolved the issue.

@analogrelay
Copy link
Contributor

Sounds like this issue is because of how Azure's CORS settings work. It looks like it doesn't properly support allowing credentials. I'm going to close this issue since this isn't something SignalR can control.

@Saravanan109587
Copy link

I am also having the issue as Given below while using angular 5 and .net Core Web API

My Startup.cs file in .net Core web Api is

signalr error

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        var connection = @"Server=DESKTOP-R31LD4G\SQLEXPRESS;Database=Tracker;Trusted_Connection=True;";
        services.AddDbContext<TrackerContext>(options => options.UseSqlServer(connection));

        services.AddElmahIo(o =>
        {
            o.ApiKey = "23debea1aa4041d8943b2d97f241f56a";
            o.LogId = new Guid("498cf9fd-cec0-4c21-bb85-c4382c45e218");
        });

        services.AddCors();
 
        services.AddElmahIo(o =>
        {

            o.WebProxy = new System.Net.WebProxy("localhost", 8888);
        });

     services.AddCors(options => options.AddPolicy("CorsPolicy",
     builder =>
     {
         builder.AllowAnyMethod().AllowAnyHeader()
                .WithOrigins("*")
                .WithMethods("*")
                .WithHeaders("*")
                
              
                .DisallowCredentials();
     }));

        services.AddSignalR();




    }

  
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactoryloggerFactory)
    {
        loggerFactory.AddLog4Net();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
           routes.MapRoute(
                name: "default",
                template: "{controller=Tracker}/{action=Index}/{id?}");
        });

      app.UseCors(builder => builder
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials()
        
        );
        app.UseElmahIo();
        app.UseSignalR(routes =>
        {
            routes.MapHub<TestSignalHub>("/TicketManagerHub");
        });

    }

@Saravanan109587
Copy link

I am Getting 204 status as in image
image

@analogrelay
Copy link
Contributor

The 204 request is expected, it's the CORS pre-flight request checking the access control headers associated with the URL.

Can you provide a full network trace from Chrome rather than just screenshots? We need to see much more detail about the requests to identify a possible issue.

@Saravanan109587
Copy link

Request Header::

OPTIONS /TicketManagerHub/negotiate HTTP/1.1
Host: localhost:62659
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/67.0.3396.99 Safari/537.36
Access-Control-Request-Headers: x-requested-with
Accept: /
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

Response Header::

HTTP/1.1 204 No Content
Vary: Origin
Server: Kestrel
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: x-requested-with
Access-Control-Allow-Origin: http://localhost:4200
X-SourceFiles: =?UTF-8?B?RDpcSXNzdWVUcmFja2VyXElzc3VlVHJhY2tlcl9BUGlcVGlja2V0VHJhY2tlclxUaWNrZXRUcmFja2VyXFRpY2tldE1hbmFnZXJIdWJcbmVnb3RpYXRl?=
X-Powered-By: ASP.NET
Date: Wed, 04 Jul 2018 01:18:40 GMT

@Saravanan109587
Copy link

I have opened connection in client like:

let conn = new HubConnectionBuilder()
  .withUrl("http://localhost:62659/TicketManagerHub")
  .configureLogging(LogLevel.Information)
  .build()
 conn.start()
  .then(res => {
    console.log('connection started');
  })
    .catch(err => {
      console.error((err));
    })

@Saravanan109587
Copy link

@anurse Is there any problem in connection ??

@littleowlnest
Copy link

Receiving this error message as per previous posters:

Failed to load http://sferic-performance-api.com/signalr/negotiate: 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'. Origin 'http://sferic-performance-app.com' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

This is the code for my Startup.cs in my API that contains the CORS policy

` public void ConfigureServices(IServiceCollection services)
{

        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        services.AddDbContext<SfericContext>(options =>
            options.UseSqlServer(connectionString));


        services.AddMvcCore(options => {
            options.Filters.Add(typeof(ValidateModelStateAttribute));
            })
            .AddAuthorization()
            .AddJsonFormatters();

        services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "http://secure.mysite.com";
                options.RequireHttpsMetadata = false;

                options.ApiName = "secureapi";
            });

        services.AddCors(options =>
        {
            // this defines a CORS policy called "default"
            options.AddPolicy("default", policy =>
            {
                policy.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
            });
        });

        services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app)
    {
        
        app.UseAuthentication();
        app.UseCors("default");
        app.UseSignalR(routes =>
        {
            routes.MapHub<MessageHub>("/signalr");
        });

        app.UseMvc();
    }`

The hub javascript is setup like this:

const connection = new signalR.HubConnectionBuilder() .withUrl("http://sferic-performance-api.com/signalr") .build();

I'm attaching my HAR file.

sferic-performance-app.com.zip

@littleowlnest
Copy link

@anurse Not sure if this issue is considered still open, since the last comment before mine implies something is ongoing.

@analogrelay
Copy link
Contributor

@littleowlnest Is ASP.NET Core the only system handling CORS requests? I ask because the HAR file you sent does not show the Access-Control-Allow-Credentials header despite your call to AllowCredentials. There is a known issue with Azure App Service's built-in CORS support where it doesn't set this header properly.

@littleowlnest
Copy link

@anurse Yes, it is the only thing handling CORS. It's not running on Azure. I've tried setting CORS using a policy and without i.e. defining the policy in .AddCors and using it in .UseCors

Tried having it .AllowAnyOrigin() and .WithOrigin("http://sferic-performance-app.com") specified and I still get the same error message. Does this imply that it is not picking up this CORS definition?

I might try some other CORS requests outside of SignalR and see if they yield the same results. It would lead me to determine if this is actually a SignalR issue or a CORS issue. Will revert once done.

@littleowlnest
Copy link

@anurse I'm putting this down to a local environment issue, maybe an interaction between Kestrel and IIS?! I updated the logging to try and provide more information and also changed the name of the log file along the way. I noticed that it didn't change, leading to the conclusion that the new code was never been in play to correct the CORS config. Recycled the IIS app pool and that resolved the stale binaries (although IIS would have already restarted multiple times). Ran into a websockets error, which was quickly resolved by adding it to IIS. Thanks for your help, consider anything I had on this issue resolved.

@eduherminio
Copy link

eduherminio commented Jul 9, 2018

Same problem here after updating from 1.0.0-preview1-final to 1.0.0, not running on Azure either.
Solved by adding a missing .AllowCredentials(), which didn't seem to be needed in pre-release versions.

@Saravanan109587
Copy link

I am getting 405 status

image

My startup.cs

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseFileServer();

        app.UseSignalR(routes =>
        {
            routes.MapHub<TestHub>("/chat");
        });
        app.UseMvc();
    }
}

And i am using .netCore 2.1
I could not connect server from angular client(@aspnet/signalR)

@Saravanan109587
Copy link

My Application is Here ,

@BrennanConroy
Copy link
Member

@eduherminio
Copy link

My Application is Here ,

@Saravanan109587 Your server works flawlessly, and your client issues don't seem to be related to SignalR.
I managed to get it working on my machine, have a look at https://github.com/Saravanan109587/SignalR_AspnetCore_Angular5/pull/1

@Saravanan109587
Copy link

@eduherminio now i am getting 204 status as previous
image

@Saravanan109587
Copy link

@BrennanConroy i have included my network Trace here

@eduherminio
Copy link

As I posted in that PR, and in case anyone else can find it useful, I updated my simple example of a server and two clients (C#, JS), which you can use to test your own ones as suggested.

I managed to connect to your server using my client without major issues.

@Saravanan109587
Copy link

@eduherminio i am using angular client @aspnet/signalr: "^1.0.0",, I couldn't find version 1.0.2

@Saravanan109587
Copy link

I cannot understand what this 204 status code means here,Can any one clarify that.

@ericbrunner
Copy link

@BrennanConroy What I didn't know ist that:

SignalR is not compatible with the built-in CORS feature in Azure App Service.

from your posted doc

I removed ALLOWED ORIGINS from CORS in App Service (Azure Portal) and enabled CORS in Startup.cs as mentioned from @davenewza and now I get that

image

In API App Service the setting is now empty:

image

In Startup.cs I added the code that way:

image

image

Hope you can help me.

@analogrelay
Copy link
Contributor

That error appears unrelated to CORS configuration. Also, since this issue is closed, I recommend you open a new one since it's very easy for discussions on closed issues to get lost (since they are closed and not part of our regular triage and bug review process).

Could you use the Diagnostics Guide to collect server and client-side logs as well as a network trace and file a new bug with your question?

@ericbrunner
Copy link

@anurse Sure. Thanks for the guidance.

@ericbrunner
Copy link

@anurse File a new issue regarding the connection issues here

@enginnerFrankLiu
Copy link

I feel so pain~ can you help me,

image

image

image

image

@ericbrunner
Copy link

@enginnerFrankLiu Your request comes from http://gameservice.com:8060. So add that to your Access-Control-Allow-Origin and it should work. If you host your app in Azure then don't cnfigure CORS there. Only in your code. If it doesn't work add that to your StartUp.cs ConfigureServices method

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

and that in Configure method.

app.UseCors("CorsPolicy");

before app.UseMvc();

And remove the customHeader setting for Access-Control-Allow-Origin . But that is not a SignalR issue.

@enginnerFrankLiu
Copy link

@ericbrunner firstly thanks your attention for my issue; it does't work; I use switchHost to switch http://gameservice.com:8060 to localhost,that means http://gameservice.com:8060 ==127.0.0.1:8000; you can see pic:

Access-Control-Allow-Origin:127.0.0.1:8000

ps: I user asp.net mvc 5 no ConfigureServices method

what should i do next ?

it really make me so pain.....help

@ericbrunner
Copy link

I guess you are in the wrong forum. MVC5 is not ASP.NET CORE and thereforr not Asp.Net Core SignalR. Have you tried setting http://gameservice.com:8060/ in your CORS HEADER von server side?

@enginnerFrankLiu
Copy link

enginnerFrankLiu commented Aug 8, 2018

@ericbrunner

I use wepback to build the dev; the default host is :127.0.0.1:8000; my api is http://gameservice.com:8060/(127.0.0.1:8060)

I update webconfig set Access-Control-Allow-Origin value="*" or value="http://127.0.0.1:8000"

all api work well, resovle the corss domain ;but signalr run into corss domain problem:

if i put url(http://gameservice.com:8060/signalr/DashBoardUserHub/negotiate) in web brower,

it response
image

the singalr work well,

“MVC5 is not ASP.NET CORE” ; you are right;

my situation is

mvc5 + using Microsoft.AspNet.SignalR; + @aspnet/signalr

i don't whether is compatible or not;

here is packetage info
image

@enginnerFrankLiu
Copy link

enginnerFrankLiu commented Aug 8, 2018

@ericbrunner

add Access-Control-Allow-Credentials" value="true" to webconfig

resovle the cross domain problem,

thanks for your attention for my issue~

@analogrelay
Copy link
Contributor

my situation is

mvc5 + using Microsoft.AspNet.SignalR; + @aspnet/signalr

This is not compatible. If your server is using the Microsoft.AspNet.SignalR package you will need to use the signalr NPM package (as opposed to @aspnet/signalr). Also, please post questions/issues for that library to https://github.com/SignalR/SignalR/

@graforlock
Copy link

graforlock commented Aug 16, 2018

Same issue here, my setup:

  • macOS High Sierra
  • .NET Core version 2.1.302
  • SignalR version 1.0.2
  • @aspnet/signalr version 1.0.2

No matter what, the CORS policy doesn't seem to apply. I was doing it off the official tutorial https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.1&tabs=visual-studio and then went to Next Steps section in the bottom that talks about CORS only to find out it doesn't work.

@BrennanConroy
Copy link
Member

Could you make a new issue and provide some code showing your CORS setup and describe the issue you're having.

@ghost
Copy link

ghost commented Aug 16, 2018

@graforlock Try that, should work.

In StartUp.cs ConfigureServices method

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

and that in Configure method.

app.UseCors("CorsPolicy");
before app.UseMvc();

Remove CORS setting from Azure App Service if hosted there.

@graforlock
Copy link

graforlock commented Aug 20, 2018

I am trying this locally. Still doesn't work, setting AllowAnyOrigin causes CORS exception just as withOrigins. Looks like CORS policy is not applied at all.

@ghost
Copy link

ghost commented Aug 20, 2018

@graforlock

  1. If you run server and client locally you dont need CORS enabled.
  2. You mentioned : macOS High Sierra
    Maybe some Mac issue. Can you try to run same app in VS2017 on Windows?
  3. Post the CORS exception (console logs, screebshots)
  4. Your app code posted here would help a lot to be able to help you!

@graforlock
Copy link

graforlock commented Aug 20, 2018

Yes locally via localhost, but different apps, and ports is still CORS.

I am trying to replicate a real production scenario, not making a backend for frontend style application.

Point 2. is beyond question, I have no intent working on Windows just because it works there.

But what I might try to do is to create a minimal example and post the issue, but its some work, so probably later today. Here, we would probably see whether the issue is Mac, if this works for you.

@analogrelay
Copy link
Contributor

@graforlock If you are still seeing this issue, please file a new issue and include the content of your Startup.cs. The CORS scenario you describe should absolutely work fine in macOS, reproducing on Windows is not necessary.

@ericbrunner
Copy link

@graforlock I am a user like you, just wanted to help. I disconnect now. I had some proxy server issues on Mac

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
status: Investigate Investigation item
Projects
None yet
Development

No branches or pull requests