1

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

Bunty Choudhary
  • 185
  • 1
  • 3
  • 11
  • Seems about right to me, what's wrong with that code? – devcrp May 21 '20 at 09:50
  • Yeah it looks correct, could you specify a bit more what you want to achieve? – Luka Rakic May 21 '20 at 09:51
  • 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 May 21 '20 at 09:53
  • @devcrp It is working with if I change it to services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); – Bunty Choudhary May 21 '20 at 09:57
  • Can I pickup the values "http://localhost:4200", "http://localhost:44349" from app setting as well? – Bunty Choudhary May 21 '20 at 10:48

1 Answers1

4

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.

Sahil Sharma
  • 1,813
  • 1
  • 16
  • 37
  • Can I pickup the values "http://localhost:4200", "http://localhost:44349" from app setting as well? – Bunty Choudhary May 21 '20 at 10:45
  • Yes, put in a comma separated string in app.settings and retrieve later. – Sahil Sharma May 21 '20 at 10:48
  • I just put "AllowedHosts": [ "http://localhost:4200" ], in app setting and get like as below, but didn't work services.AddCors(opt => { var origins = Configuration .GetSection("AllowedHosts") .Get(); opt.AddPolicy("CorsPolicy", builder => builder .WithOrigins(origins) .AllowAnyMethod() .AllowAnyHeader() .Build()); }); – Bunty Choudhary May 21 '20 at 10:51
  • Read this: https://stackoverflow.com/questions/46940710/getting-value-from-appsettings-json-in-net-core – Sahil Sharma May 21 '20 at 10:54