0
votes

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

1
Seems about right to me, what's wrong with that code? - devcrp
Yeah it looks correct, could you specify a bit more what you want to achieve? - LucaBNW
I am getting exception Access to XMLHttpRequest at 'http://localhost:44314/api/Reservation' from origin 'http://localhost:4200' 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. while calling it from another application - Bunty Choudhary
@devcrp It is working with if I change it to services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); - Bunty Choudhary
Can I pickup the values "localhost:4200", "localhost:44349" from app setting as well? - Bunty Choudhary

1 Answers

2
votes

The order of precedence for Cors should be before adding controllers. It should be added as define in the official documentation: https://docs.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.