.NET 5.0 API - Allow CORS requests from any origin and with credentials
Tutorial built with .NET 5.0
This is a quick post to show how to configure a .NET 5.0 API to allow CORS requests from any origin as well as with credentials.
I received the following error after setting credentials: 'include'
for CORS requests sent from a React app to a .NET 5.0 API running on a different domain, and configuring CORS on the API to .AllowAnyOrigin()
and .AllowCredentials()
.
System.InvalidOperationException: The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the CORS policy by listing individual origins if credentials needs to be supported.
I needed credentials allowed so the client could include cookies in requests to the .NET API, but as the error says you can't use the .AllowAnyOrigin()
CORS configuration method together with .AllowCredentials()
, because .AllowAnyOrigin()
specifies a wildcard for the allow origin access control http header (Access-Control-Allow-Origin: *
).
To fix the issue and still allow any origin you can use this method instead: .SetIsOriginAllowed(origin => true)
.
The lambda function that you pass to the .SetIsOriginAllowed()
method returns true if an origin is allowed, so always returning true allows any origin to send requests to the api. The allow origin access control http header returned when using this method contains the origin that sent the request, not a wildcard, e.g. Access-Control-Allow-Origin: http://localhost:4200
.
Example .NET Startup.cs
This is an example Startup.cs file a .NET 5.0 API that supports CORS requests from any origin with credentials. The methods we're interested in are called on lines 26
and 27
.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using WebApi.Authorization;
namespace WebApi
{
public class Startup
{
// add services to the DI container
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
}
// configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
// global cors policy
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials()); // allow credentials
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.UseEndpoints(x => x.MapControllers());
}
}
}
Need Some .NET Help?
Search fiverr for freelance .NET developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!