Source

Tutorial built with ASP.NET Core 3.1

This is a quick post to show how to configure an ASP.NET Core API to allow CORS requests from any origin as well as with credentials.

I ran into the below error after setting withCredentials: true for CORS requests sent from an Angular app to a .NET Core 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 to include cookies in requests to the api, but as the error says you can't use the .AllowAnyOrigin() CORS configuration method together with the .AllowCredentials() method, because it 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 Startup.cs
This is an example Startup.cs file an ASP.NET Core 3.1 API that supports CORS requests from any origin with credentials. The methods we're interested in are called on lines 33 and 34.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WebApi
{
    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.AddCors();
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to 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

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(x => x.MapControllers());
        }
    }
}