KiddoDeveloper
KiddoDeveloper

Reputation: 628

SignalR, ReactJs and Dotnet Core: CORS Issue

I am trying to implement SignalR in a Dotnet Core + ReachtJS web application. While calling the API and making a SignalR connection, I am facing a CORS issue.

ReactJS SignalR Connection Code:

useEffect(() => {
    const newConnection = new HubConnectionBuilder()
        .withUrl('https://myapi.com/hubs/signalrconn')
        .withAutomaticReconnect()
        .build();

    setConnection(newConnection);
}, []);

Scenario 1: Below configuration works for a specific server. I am able to make a SignalR connection. Below is my config code of API:

services.AddCors(options =>
        {
            options.AddPolicy("prod",
                builder => builder.WithOrigins("https://reactapp.com")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials());

        }); 
app.UseCors("prod"); // This line is part of Configure method.

The issue with the above approach: This works only for a singal machine i.e. reactapp.com. I would like to CORS enable for publicly. So that I can deploy my react webapp on any webserver and it can access webapi. So, I changed my CORS config:

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

But it will give me the below error.

enter image description here

How I can enable CORS for SignalR connection from any webserver?

EDIT: Below change in the react code, worked for me.

 useEffect(() => {
    const newConnection = new HubConnectionBuilder()
        .withUrl('https://myapi.com/hubs/signalrconn', {
            withCredentials: false
        })
        .withAutomaticReconnect()
        .build();

    setConnection(newConnection);
}, []);

Upvotes: 0

Views: 754

Answers (1)

Brennan
Brennan

Reputation: 1933

You have a couple options.
a. Configure all origins that you want to allow via WithOrigins
b. Set withCredentials to false on the javascript client https://learn.microsoft.com/aspnet/core/signalr/configuration?view=aspnetcore-5.0&tabs=javascript#configure-additional-options

Upvotes: 3

Related Questions