Cross-Origin Resource Sharing (CORS) is a process that protects your APIs from defined domains, method types, or headers, and the properties are defined while adding the CORS policy.
Please find below 10 tips to configure CORS in .NET applications.
To set up the handshake between the UI and the API layer, a basic understanding of how CORS headers are required, such as
Example: The CORS headers define which domains can access your APIs.
access-control-allow-origin: https://example.com
You can configure CORS in Program.cs by using CORS middleware, as shown below.
Example
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
{
builder.WithOrigins("https://example.com")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors("AllowSpecificOrigin"); // Apply the CORS policy
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
To specify the array of domains that are allowed to access the APIs that validate any unauthorized domain request to your API server.
Use WithOrigins method to specify the list of domains comma-separated, as shown below.
Example
builder.WithOrigins("https://example1.com", "https://example2.com")
.AllowAnyMethod()
.AllowAnyHeader();
One can also allow only specific REST methods using WithMethods, which helps filter out which type of API methods are allowed.
Example
builder.WithOrigins("https://example.com")
.WithMethods("GET", "POST") // Allow only GET and POST methods
.AllowAnyHeader();
A developer can also restrict headers when using WithHeaders.
Example
builder.WithOrigins("https://example.com")
.AllowAnyMethod()
.WithHeaders("Content-Type", "Authorization");
Use AllowCredentials() only if your application supports credentials via Cookie Authentication.
Example
builder.WithOrigins("https://example.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials(); // Allows credentials
The CORS policy can be applied globally, i.e., on the application level as well as at the controller/action level.
Example
[EnableCors("AllowSpecificOrigin")]
public class MyController : ControllerBase
{
// Controller actions
}
Preflight requests are sent by the browser to check permissions before making the actual requests. Ensure that the CORS policy is properly configured and allows OPTIONS requests.
Example: ASP.NET Core automatically handles preflight requests if CORS is properly configured.
CORS policy can be applied conditionally based on the environment, which provides flexibility to implement different policies as per the environment, such as DEV, QA, or Production
Example
if (env.IsDevelopment())
{
builder.WithOrigins("http://localhost:3000") // Development origin
.AllowAnyMethod()
.AllowAnyHeader();
}
else
{
builder.WithOrigins("https://production.com") // Production origin
.AllowAnyMethod()
.AllowAnyHeader();
}
CORS policy needs to be updated as per your newer application requirements. Let’s say a newer application is supposed to connect to CORS-implemented REST API, then you need to configure the domain, method or header as per the new application requirements.
Monitor your application’s request patterns and adjust CORS settings as needed to maintain security and functionality.
By following these tips, developers can effectively implement and manage CORS in your .NET applications, ensuring secure and controlled access to API resources from multiple origins.
Thank you for being a part of the C# community!