I'm having problem setting up Cors policy in my ASP.NET core project.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMemoryCache();
}
I've tried adding app.UseCors("AllowAll"); in Configure(IApplicationBuilder app, IHostingEnvironment env), tried [EnableCors("AllowAll")]before controller declaration:
[Route("api/[controller]")]
[ApiController]
[EnableCors("AllowAll")]
public class TestController : ControllerBase
and before method declaration:
[HttpPost]
[EnableCors("AllowAll")]
public JsonResult Post([FromBody] dynamic request)
and no luck, I'm keep getting "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at..."
Maybe someone can help me?
I know this is too late, but can help someone,
using CorsMiddleware in specified order is matters
app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();
app.UseResponseCaching();
The call to UseCors must be placed after UseRouting, but before
UseAuthorization.
When using Response Caching Middleware, call
UseCors before UseResponseCaching
Related
Currently I am having problem about has been blocked by CORS policy: No 'Access-Control-Allow-Origin'.
I've tried to fix it in many ways but it still doesn't seem to work.
Hope someone can show me how to fix it.
My code:
File Startup.cs
public void ConfigureServices(IServiceCollection services)
...
services.AddCors(options =>
{
options.AddPolicy(name: "AllowAnyOrigin",
builder =>
{
builder.WithOrigins("http://localhost:3000")
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
...
}
public void Configure(IApplicationBuilder app){
...
app.UseCors("AllowAnyOrigin");
...
}
Controller
[HttpPost]
[EnableCors("AllowAnyOrigin")]
public async Task<IActionResult> ChangeInviteSponsors([FromForm] ChangeInviteSponsorsModel changeInviteSponsorsModel)
{
string userId = User.GetUserId();
return Ok(await _inviteSponsorsService.ChangeInviteSponsors(changeInviteSponsorsModel, userId));
}
Error: Access to XMLHttpRequest at 'https://localhost:5560/api/InviteSponsors/ChangeInviteSponsors' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Help me please. Thank you!
To fix the CORS policy violation issue, try this.
Also, the order of connecting services in the Configure method is very important.
First, in the ConfigureServices method, the first method before controller mapping should be
services.AddCors();
Second, to allow CORS, change the Configure method. Add this code after the UseRouting and before Middlewares and Controller mappings.
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
This will allow any requests from any external domains.
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
}
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!
I tried to avoid posting this question as there are so many others like, but after trying what seems like every combination none have solved my issue.
The Problem
My angular application CAN POST to my web API when it's running locally on IIS EXPRESS. But when the API is deployed to IIS my Angular app CANNOT POST to it. However it can successfully perform a GET request in both environments.
The Error
Access to XMLHttpRequest at 'https://mySite:1234/api/v1/postData' from origin 'https://mySite:1233' 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.
What I've tried/the code
Both applications run on different ports so I understand why I need to configure CORS and after quite a bit of reading I found that a pre-flight request is not made for GET requests (as covered in the Mozilla Docs), so that would explain why the GET request succeeds. The Mozilla docs lead me to believe that my POST does not come under the simple request category as it require authorisation, but that does not answer way it works on IIS EXPRESS and not on IIS (I assume express is a bit less strict?).
After following the official docs and NOT being able to get it to work then looking at various SO posts and trying various options, I've come to a dead-end and really hope someone can point out where I've gone wrong
Startup.cs
public class Startup
{
private const string ALLOWED_ORIGINS = "allowedOrigin";
...other stuff...
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: ALLOWED_ORIGINS,
builder =>
{
builder.WithOrigins("https://myLocalSite:1233", "https://myDeployedSite:1233")//these values are retrieve from config
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.AddControllers()
....other stuff...
services.AddMvc(o =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
o.Filters.Add(new AuthorizeFilter(policy));
});
....other stuff...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...other stuff...
app.UseRouting();
app.UseCors(ALLOWED_ORIGINS);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
...other stuff...
}
}
The controller
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class PostDataController : ControllerBase
{
...other stuff...
[HttpPost]
public async Task<SomeResponse> Post(SomeRequest sr)
{
...other stuff...
}
}
Finally
I have not added any angular code as I believe that the issue is in my API set up. I will be happy to add the code if needed though
Try putting AddMvc BEFORE "AddCors".
Sanity checks: start with AllowAnyOrigin, and work your ways to more granular definition
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
public void Configure(IApplicationBuilder app)
{
app.UseCors(policy => policy.WithOrigins(ALLOWED_ORIGINS));
}
Looks like you have those (above).
Do you have (below) ?
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CorsOptions>(options =>
{
options.AddPolicy(
"AllowAnySimpleRequest",
builder =>
{
builder.AllowAnyOrigin()
.WithMethods("GET", "POST", "HEAD");
});
Check out this file for a better "full context" code. https://csharp.hotexamples.com/site/file?hash=0x8b07b2262d54348025f4b69ad1c3a6e517321a0d14cca0e0bf05aed12f88424f&fullName=Startup.cs&project=psilon2000/LUV
I've installed NuGet package Microsoft.AspNetCore.Cors 2.2.0
then in my .net core webAPI Startup.cs I have done the following:
public void ConfigureServices(IServiceCollection services) {
......
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(options =>
options.WithOrigins("http://localhost:52556")
.AllowAnyMethod()
.AllowAnyHeader());
app.UseMvc();
}
Then when I send post request from my angular app in console I see this error:
Access to XMLHttpRequest at 'http://localhost:52556/api/PaymentDetail'
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.
I thought I've enabled CORS but it seems that something is blocking it. What can be done to solve this problem ?
Try this way. Ithink it's because you are allowing URLs with "http://localhost:52556" only. Using "*" will enable all URLs and if you can want you can limit it to any specific one.
public void ConfigureServices(IServiceCollection services)
{
.........................
services.AddCors(options =>
{
options.AddPolicy("NoRestrictions",
builder => builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod());
});;
...............
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<AppServerSettings> appServerSettings)
{
..........
app.UseCors("NoRestrictions");
..........
}
You are setting Origin for you asp host.
Just replace this line
options.WithOrigins("http://localhost:52556")
with
options.WithOrigins("http://localhost:4200")
I solved same problem in C# by annotations/attributes,
[System.Web.Http.Cors.EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class StudentsController : ApiController{}
in MVC,
use,
// For Action,
[HttpGet]
[EnableCors("AllowSpecificOrigin")]
public IEnumerable<string> Get(){}
// For Controller,
[Route("api/[controller]")]
[EnableCors("AllowSpecificOrigin")]
public class ValuesController : ControllerBase{}
in your case, replace with this If specific to port number process 4200,
options.WithOrigins("http://localhost:4200");
or you can put No Restrictions,
app.UseCors("NoRestrictions");// To config
// To service
services.AddCors(options =>
{
options.AddPolicy("NoRestrictions",
builder => builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod());
});
Checks whats the origin,
1) checks port number (e.g. 8080 or 8888)
2) domain and sub domain (e.g. google.com or google.net)
3) schema (e.g. http or https)
register origin,
go inside Startup.ConfigureServices and call services.AddCors();
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
enable cors now,
go Startup.Configure and call app.UseCors(builder =>
builder.WithOrigins("http://google.com"));
I am trying to enable "*" CORS headers on application startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(opts =>
{
opts.Filters.Add(new AuthorizationFilterFactory());
});
services.AddCors(opts => opts.AddPolicy("*",
builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()));
services.AddSwaggerGen();
services.ConfigureSwaggerGen(opts =>
{
opts.SingleApiVersion(new Info { Version = "v1", Title = "CORS app" });
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("*");
app.UseSwagger();
app.UseSwaggerUi();
app.UseMiddleware(typeof(ExceptionHandlingMiddleware));
app.UseMvc();
}
The headers don't show up. Tried to request my resources with Ajax from a different domain and I am getting:
415 (Unsupported Media Type)
Tried with JS:
$.post("http://example.com/some-api", JSON.stringify({"name": "hello"}));
Any ideas? Maybe something wrong with the order of middleware registrations?
UPDATE: Apparently this CORS library adds headers only when it identifies XHR cross-origin requests. It suddenly started working for me. Thanks everyone for your comments.