Search code examples
c#restasp.net-corecorscross-domain

How to enable CORS in Asp.Net Core 3.0 WebAPI


I want to enable CORS with Asp.Net Core 3.0 API project. This is the basic generated Asp.Net Core Api template. Everything is default from the template, except I added CORS settings from the documentation

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.AddControllers();
        services.AddCors(opt =>
        {
            var origins = Configuration
                .GetSection("AllowedHosts")
                .Get<string[]>();

            opt.AddPolicy("CorsPolicy", builder => builder
                    .WithOrigins(origins)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .Build());
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("CorsPolicy");
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

What should I set up for getting corret CORS in .net core web api? Allowed host is : enter image description here


Solution

  • The order of precedence for Cors should be before adding controllers. It should be added as define in the official documentation: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

    Follow this code:

    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(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder
                     .WithOrigins("http://localhost:4200", "http://localhost:44349")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    //.AllowCredentials());
                     );
            });
    
          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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
           
            app.UseHttpsRedirection();    
            app.UseRouting(); 
            
            app.UseCors("CorsPolicy");   
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
    

    As per the official documentation, it must be noted that:

    Specifying AllowAnyOrigin and AllowCredentials is an insecure configuration and can result in cross-site request forgery. The CORS service returns an invalid CORS response when an app is configured with both methods.