How to enable Cross-Origin Requests (CORS) in ASP.NET Core?
Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction is called the same-origin policy. The same-origin policy prevents a malicious site from reading sensitive data from another site. Sometimes, you might want to allow other sites to make cross-origin requests to your app. For more information, see the Mozilla CORS article.
Cross Origin Resource Sharing (CORS):
- Is a W3C standard that allows a server to relax the same-origin policy.
- Is not a security feature, CORS relaxes security. An API is not safer by allowing CORS. For more information, see How CORS works.
- Allows a server to explicitly allow some cross-origin requests while rejecting others.
- Is safer and more flexible than earlier techniques, such as JSONP.
Same origin
Two URLs have the same origin if they have identical schemes, hosts, and ports (RFC 6454).
These two URLs have the same origin:
https://example.com/foo.htmlhttps://example.com/bar.html
These URLs have different origins than the previous two URLs:
https://example.net: Different domainhttps://www.example.com/foo.html: Different subdomainhttp://example.com/foo.html: Different schemehttps://example.com:9000/foo.html: Different port
Enable CORS
There are three ways to enable CORS:
- In middleware using a named policy or default policy.
- Using endpoint routing.
- With the [EnableCors] attribute.
Using the [EnableCors] attribute with a named policy provides the finest control in limiting endpoints that support CORS.
Warning
UseCors must be called in the correct order. For more information, see Middleware order. For example, UseCors must be called before UseResponseCaching when using UseResponseCaching.
Each approach is detailed in the following sections.
CORS with named policy and middleware
CORS Middleware handles cross-origin requests. The following code applies a CORS policy to all the app's endpoints with the specified origins:
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
// services.AddResponseCaching();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
app.Run();
Comments
Post a Comment