ASP.NET 5: Access-Control-Allow-Origin in response - c#

From what I understand, when enabled CORS accordingly, the response model should include the following header information (provided that I want to allow everything):
Access-Control-Allow-Origin: *
Access-Control-Allow-Method: *
Access-Control-Allow-Header: *
Enabling it in Startup:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddCors();
services.ConfigureCors(options =>
{
options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
});
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//...
app.UseCors("AllowAll");
//...
}
The problem is that none of these headers are returned and I get the following error when trying to request from the API:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.

Make sure you add app.UseCors before app.UseMvc in your Startup.Configure method, because you need the CORS middleware to be applied before the MVC middleware.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
//Add CORS middleware before MVC
app.UseCors("AllowAll");
app.UseMvc(...);
}
Otherwise the request will be finished before the CORS middleware is applied. This is because UseMvc calls UseRouter which ends up adding the RouterMiddleware, and this middleware only executes the next configured middleware when a route handler wasn't found for the request.

In .Net Core Web API 5.0 in Configure method you have to add app.UseCors before other methods, like that:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
...
}
//add CORS
app.UseCors();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

Related

How to make ajax call from .Net Core API in Cross Origin (CORS)? [duplicate]

From what I understand, when enabled CORS accordingly, the response model should include the following header information (provided that I want to allow everything):
Access-Control-Allow-Origin: *
Access-Control-Allow-Method: *
Access-Control-Allow-Header: *
Enabling it in Startup:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddCors();
services.ConfigureCors(options =>
{
options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
});
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//...
app.UseCors("AllowAll");
//...
}
The problem is that none of these headers are returned and I get the following error when trying to request from the API:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
Make sure you add app.UseCors before app.UseMvc in your Startup.Configure method, because you need the CORS middleware to be applied before the MVC middleware.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
//Add CORS middleware before MVC
app.UseCors("AllowAll");
app.UseMvc(...);
}
Otherwise the request will be finished before the CORS middleware is applied. This is because UseMvc calls UseRouter which ends up adding the RouterMiddleware, and this middleware only executes the next configured middleware when a route handler wasn't found for the request.
In .Net Core Web API 5.0 in Configure method you have to add app.UseCors before other methods, like that:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
...
}
//add CORS
app.UseCors();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

AddCors is not working in asp.net 5.0. How do I enable it?

So my problem is that I tried to enable the CORS, followed the tutorial and it is still not working. My startup.cs looks like this (I include methods to which I tried enabling CORS). Any help would be appreciated:
ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options=>options.AddDefaultPolicy(builder=>builder.AllowAnyOrigin()));
services.AddControllers();
services.Add(new ServiceDescriptor(typeof(ApplicationDbContext),
new ApplicationDbContext(Configuration.GetConnectionString("DefaultConnection"))));
}
And then I try to use cors in the Configure method.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
I use the newest .NET core version.
Error specifically is:
Access to XMLHttpRequest at 'http://localhost:5000/api/cities' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
Thanks in advance.
Try to use this syntax and assign name to the policy
services.AddCors(o => o.AddPolicy("AllowAnyOrigins", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
.......
app.UseRouting();
app.UseCors("AllowAnyOrigins");
app.UseAuthorization();

Configure Strict Cors .Net Core 3.1

I have a public analytics web api (.Net Core 3.1) that captures basic analytics from my various web apps and sites (page views, etc). I'd very much like to configure cors in a more strict manner as I am well aware of the origins from where traffic should come. It's worth noting that I'm updating this application from .Net Core 2.2 to .Net Core 3.1.
I have the following method in my Startup.cs file
public void ConfigureServices(IServiceCollection services)
{
...
ConfigureCors(services);
}
private void ConfigureCors(IServiceCollection services)
{
// https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins(AppConfiguration.CorsOrigins)
.AllowAnyMethod()
.AllowAnyHeader());
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
});
}
AppConfiguration is a class I use to handle configurations and it grabs json values using the following:
public string[] CorsOrigins => _config["CorsOrigins"].Split(',');
In appsettings.Development.json, I have "CorsOrigins": "*"
I'd very much like to specify strict origins in the appsettings.Production.json and appsettings.Staging.json files.
E.g.
"CorsOrigins": "https://subdomain.example.com,https://www.example.com,https://example.com", but on deployment, I get a status of 502 whenever by websites/apps hit the various endpoints.
"CorsOrigins": "*" works on local so there can't be anything wrong with the Startup.cs file as far as I'm aware.
Update: "CorsOrigins": "*" actually does not work for the staging or production environments either. Now I'm even more confused. To be clear, this is a cors question. The following worked fine before upgrading to .Net Core 3.1:
private void ConfigureCors(IServiceCollection services)
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
Take care to place the UseCors at the right location. From the docs:
The call to UseCors must be placed after UseRouting, but before
UseAuthorization.
As noted in the comments, allowing "*" as origin isn't allowed with AllowCredentials.
Here's a working example of a CORS configuration from my ASPNET Core 3.1 project. It does the config in the Configure method instead of ConfigureServices, but same content:
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
// etc
}
public void Configure(IApplicationBuilder app)
{
// other configs
app.UseRouting();
// CORS configuration. Expects allowed origins as comma-separated list in config under 'Cors:AllowedOrigins'.
string configuredOrigins = Configuration["Cors:AllowedOrigins"] ?? throw new ArgumentNullException("Cors:AllowedOrigins");
string[] origins = configuredOrigins.Split(',', ';').Select(i => i.Trim()).ToArray();
app.UseCors(policy => policy
.WithOrigins(origins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials() // Required by SignalR
.WithExposedHeaders(CONTINUATION_HEADER_KEY) // Allow use of custom header
.SetPreflightMaxAge(TimeSpan.FromSeconds(86400))); // Allow caching for 24 hours (depends on browser)
app.UseAuthentication();
app.UseAuthorization();
// other configs
}
Sorry this is a difficult question so there could be a number of reasons it doesnt work but Ive run into a similar issue and resolved its by altering the cors invocation in the Configure() function. The Configure() function is a gets called during runtime and acts as an http request pipeline so in some cases order of execution matters (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/startup?view=aspnetcore-3.1#the-configure-method)
You could try the following:
Change the current:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors("CorsPolicy"); //Move this line
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
});
}
To:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("CorsPolicy"); // Here
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
});
}
Hence the first operation in the http pipeline would be to validate cors.
I rate this is a fair bet as from your question it sounds like you dont get an app initialise error but rather a runtime client request time error.
I dont know for certain if this will solve the problem but maybe it helps!

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 :
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.

Terminal middleware (api key check) not working with endpoint routing

I am implementing an api where on one specific POST route there must be an API key check.
The SDK is dotnet core 3.1.
When I run the API using Postman, I get the following error:
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints
I looks like the route attribute on the api controller, together with endpoint route registration are stacked...
How can this be fixed ?
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
app.UseSerilogRequestLogging();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger(Configuration);
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapApiKeyAuthentication();
endpoints.MapControllers();
});
}
(extension class)
public static IEndpointRouteBuilder MapApiKeyAuthentication(this IEndpointRouteBuilder endpoints)
{
endpoints.MapPost("/v1/xyz", endpoints.CreateApplicationBuilder()
.UseMiddleware<ApiKeyMiddleware>()
.Build())
.WithDisplayName("ApiKey");
return endpoints;
}

Categories

Resources