SignalR Access to fetch has been blocked by CORS - c#

I am currently following this basic signal R tutorial.
But because I want to use it in an existing project I split it up. The Hub is inside a different project than the client. Therefore the IP address is different. Inside the configuration of the Hub I of course enabled cors:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
services.AddSignalR();
//other configuration code
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
app.UseRouting();
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<LiveUpdating.ChatHub>("/chatHub");
});
}
However when I now try to connect to the chatHub in my client (setup is exactly the same as in the link above except that I changed the connection to var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44316/chatHub").build(); ) I get this error:
Access to fetch at 'https://localhost:44316/chatHub/negotiate?negotiateVersion=1' from
origin 'https://localhost:44341' has been blocked by CORS policy: 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'.
Shouldn't this normally work, when I add the app.UseCors as seen above. Because for all my other Rest Controllers it works fine.

Replacing the app.useCors with
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
fixes the bug

Related

How to allow cors with signalr

Working on an app with signalr, managed to solve the cors error with the connection to the API but when trying to connecto to the hub it shows the error below which won't happen when debugging on my local computer even with different port.
Access to fetch at 'http://iisServer:10079/fareg/signalr/negotiate?negotiateVersion=1' from origin 'http://iisServer' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Here is my configuration on the app
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddSignalR();//.AddMessagePackProtocol();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//add Windows authentication for http options request
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.AddDbContext<FAContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("FADB")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(options =>
{
//options.WithOrigins("http://schi-iis1zsus", "http://localhost:4200");
options.AllowAnyOrigin();
options.AllowAnyMethod();
options.AllowAnyHeader();
options.AllowCredentials();
});
app.UseSignalR(routes =>
{
routes.MapHub<Hubs.HubFA>("/signalr");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
Please help, I've looking every where but haven't get a solution to this issue.
https://learn.microsoft.com/aspnet/core/signalr/security?view=aspnetcore-5.0#cross-origin-resource-sharing
You either need to specify the origins explicitly, or remove AllowCredentials() and set withCredentials to false on the client https://learn.microsoft.com/aspnet/core/signalr/configuration?view=aspnetcore-5.0&tabs=javascript#configure-additional-options-1

Overriding global CORS policy with a different policy for signalR end point

I have a global CORS policy which is applicable for all the endpoints but I want to override this policy for the signalR hub end point.
Here is my ConfigureServices method which has a global CORS policy which I cant modify
public void ConfigureServices(IServiceCollection services)
{
// some piece of code before adding CORS
services.AddCors(o =>
{
o.AddDefaultPolicy(p =>
{
p.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// some piece of code after adding CORS
}
Here is the Configure method
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
app.UseCors();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endPoints =>
{
endPoints.MapControllers();
endPoints.MapHub<NotificationHub>("/notificationHub")
.RequireCors((builder) =>
{
builder
.WithOrigins(_configuration.GetValue<string>("Settings:ClientAppUrl"))
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
}
As it is clear that I have overwritten the CORS policy for the particular endpoint of signal which is /notificationHub.
I am getting the same CORS error in the browser as I was getting before adding the CORS policy for the /notificationHub/negotiate
Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow->Credentials' header in the response is '' which must be 'true' when the request's credentials mode is >'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the >withCredentials attribute.
Also please note that if I add AllowCredentials() method in the global CORS policy then signalR works properly but my objective here is to add the new CORS policy only for the signalR endpoint.
I am not using OWIN CORS, it is just Microsoft.AspNetCore.Cors.
I have found the fix for this. It is simple but often ignored.
The order of middleware matters here a lot. By swapping the below two middleware, I got it working.
OLD
app.UseCors();
app.UseRouting();
NEW
app.UseRouting();
app.UseCors();
If anyone facing this issue, try doing this. It would definitely work.
This doc from Microsoft supports this claim.

CORS request being rejected despite correct headers

In my ASP.Net Core 2.2 setup I have a method to create an "allow all" CORS policy
public static IServiceCollection AddAllowAllCors(this IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed(_ => true);
});
});
return services;
}
Which is added in ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAllowAllCors();
...
}
Which I activate in my Configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseCors("AllowAll");
...
}
When I try to make a PUT request from my React app, the OPTIONS request looks like this in Chrome:
But the actual PUT request fails with a 405:
This is despite the fact that the Access-Control-Allow-Origin header in the OPTIONS response to be allowed. This worked in 2.1 but doesn't in 2.2. The exact error message is:
Access to fetch at 'MY_REQUEST_URI' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I've also tried removing AllowCredentials() in the policy but that didn't make a difference.
Looks like your CORS configuration is ok. But there is no actual PUT handler. You should check your API with some kind of rest client like postman or ARC first of all and then think about CORS.
A combination of turning off the new Endpoint Routing feature and disabling the WebDav module in IIS fixed this issue for me. I believe that because of Endpoint Routing, my preflight requests were actually being handled by the WebDav module and not by my app.
To turn off Endpoint Routing, set the flag to false in .AddMvc():
services.AddMvc(options =>
{
...other options
options.EnableEndpointRouting = false;
})
public static IServiceCollection AddAllowAllCors(this IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyOrigin();
});
});
return services;
}

How to get rid of CORS in .net core 2.2?

I've updated my project to .net core 2.2 and it seems like CORS is making problems that weren't there in 2.1.
I'm running my app on this URL: http://*:5300
I've added this code in the Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
options.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader();
}));
services.AddMvc();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseCors(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader();
});
app.UseAuthentication();
app.UseMvc();
}
This didn't work, so I've added on top of it the [EnableCors] attribute on my `BaseController" class:
[EnableCors]
[Authorize]
[Produces("application/json")]
[Route("api/[controller]")]
public class BaseController : Controller
{
}
But I'm still getting this CORS error:
Access to XMLHttpRequest at 'http://192.168.15.63:5301/api/permissions/UI' from origin 'http://192.168.15.63:5302' has been blocked by CORS policy:
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'.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
What else can I do in order to completely remove CORS?
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'.
You cannot use both AllowAnyOrigin and AllowCredentials when using ASP.NET Core to respond to a CORS request.
Access to XMLHttpRequest at 'http://192.168.15.63:5301/api/permissions/UI' from origin 'http://192.168.15.63:5302' has been blocked by CORS policy
This message shows that your server is listening on http://192.168.15.63:5301, but your client is making the request from http://192.168.15.63:5302. Since the port is different, these are different origins and therefore CORS protection is used.
To allow the request to succeed, update your ASP.NET CORS configuration code to something like the following:
builder.WithOrigins("http://192.168.15.63:5302")
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader();
This configures the origin of the client as being supported by CORS - you could, of course, add this as a configuration option to the application itself (using e.g. appsettings.json), if needed.
Aside:
As you've called AddCors and configured a named policy, there is no reason to configure the same policy in the call to UseCors - you can simply pass in the name of the policy you configured earlier with AddCors:
app.UseCors("MyPolicy");

.NET Core - CORS error even after enabling CORS

I am trying to call the WebAPI method to get some data, but it throws a Cross-Origin Read Blocking (CORB) blocked cross-origin response https://localhost:44332/api/Controller/Action with MIME type text/html. even though I have enabled CORS in my ConfigureServices Method and used the policy in the Configure method in the startup
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.WithOrigins("http://localhost:4200/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
.....
app.UseCors("AllowAll");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
What could the reason be?
So, Basically as CRice and johnny commented, Internal server error are propagated as CORS Error.
Since it is good practice to handle all errors within the application, doing so will make sure 500 Internal Server Error will be intact even in the case of an exception and not be masked as CORS Error.
It can be understood better here
This might help,
Note: The URL must not contain a trailing slash (/). If the URL terminates with /, the comparison returns false and no header is returned.

Categories

Resources