How to allow cors with signalr - c#

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

Related

Issue in CORS in ASP .NET Core - The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*

I'm getting the below error
Access to XMLHttpRequest at 'http://localhost:5000/api/values/track/?name=name&time=1589425390870' from origin 'http://localhost:23456' has been blocked by CORS policy: 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.
I have configured Asp.net core app like below
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader().AllowCredentials() ;
}));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("MyPolicy");
app.UseMvc();
}
Content type: application/x-www-form-urlencoded
Can some one please help me in resolving this issue?
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'.
As error indicates that you configure your app with both AllowAnyOrigin and AllowCredentials methods, which cause that the CORS service returns an invalid CORS response.
You can modify the code to enable specific origins, like below.
builder.WithOrigins("set_specified_origins_here")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
For detailed information about "Set the allowed origins", please check following doc: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.0#set-the-allowed-origins-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 in ASP.NET Core in IIS

I found interesting problem. I deployed my ASP.NET Core REST API on IIS and when I called it, I had this error:
Access to XMLHttpRequest at 'https...' from origin 'https:...' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.
Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https:'.
but it was working few minutes ago. I checked the response header and this was there:
access-control-allow-headers: content-type,odata-maxversion,odata-version
access-control-allow-methods: GET, GET,POST,PUT,DELETE,OPTIONS
access-control-allow-origin: *, *
Then I realised I restarted the service. For some reason my code and IIS duplicate HTTP response header values every time the service is uploaded. When I delete HTTP Response Header values in IIS, it works. This is my Startup.cs code:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddControllers();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("AllPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Do you have any ideas why are the header values duplicated everytime when is the service uploaded? And do you have any ideas how to fix it?
Try moving the "app.UseCors("AllPolicy");" to right after app.UseRouting();
so that it looks like:
app.UseRouting();
app.UseCors("AllPolicy");

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");

Categories

Resources