Cookie Consent by Free Privacy Policy Generator Aktuallisiere deine Cookie Einstellungen ๐Ÿ“Œ Cross-Origin Resource Sharing (CORS) in ASP.NET Core: A Comprehensive Guide


๐Ÿ“š Cross-Origin Resource Sharing (CORS) in ASP.NET Core: A Comprehensive Guide


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

Originally published at https://antondevtips.com.

Cross-Origin Resource Sharing (CORS) is a standard in web applications that allows or restricts web pages from making requests to a domain different from the one that served the initial web page.
Today we will explore how to implement and manage CORS in ASP.NET Core applications effectively.

How CORS works

When a web page makes a cross-origin HTTP request, the browser automatically adds an Origin header to the request.
The server checks this header against its CORS policy.
If the origin is allowed, the server responds with a Access-Control-Allow-Origin CORS header.
This indicates that the request is allowed to be served on the server.

The server doesn't return an error if the CORS policy doesn't allow the request to be executed.
The client is responsible for returning error to the client and blocking the response.

CORS is a way for a server to allow web browsers to execute a cross-origin requests.
Browsers without CORS can't do cross-origin requests.

When To Use CORS

CORS should be enabled in ASP.NET Core:

  • To allow your API to be accessed from different domains
  • When your frontend and backend are hosted separately
  • To control specific resources in your application to be accessible from other domains
  • In development mode

To enable CORS in ASP.NET Core, call the AddCors method on the IServiceCollection to add it to the DI container:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigin",
        policyBuilder => policyBuilder.WithOrigins("http://example.com"));
});

And add CORS to the middleware pipeline by calling UseCors method:

app.UseCors("AllowSpecificOrigin");

Often CORS are enabled in ASP.NET Core apps only in the development mode to simplify development when frontend and backend are run on different hosts or ports.
Consider using CORS in production only when it is absolutely required

Correct Order of Middlewares When Using CORS

Here are few important tips when placing UseCors middleware:

  • UseCors middleware should be placed before UseResponseCaching due to this bug.
  • UseCors middleware should be placed before UseStaticFiles to ensure CORS headers are properly added to the static file responses
app.UseCors();
app.UseResponseCaching();
app.UseStaticFiles();

Enable CORS in WebApi Controllers

To apply CORS policies to specific endpoints, use the RequireCors method in endpoint routing configuration:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers().RequireCors("AllowSpecificOrigin");
});

You can enable or disable CORS for a specific controller:

[EnableCors("AllowSpecificOrigin")]
public class UsersController : ControllerBase
{
    // Controller methods
}

[DisableCors]
public class ProductsController : ControllerBase
{
    // Controller methods
}

You can also enable or disable CORS for different controller methods:

public class UsersController : ControllerBase
{
    [EnableCors("CorsPolicy1")]
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get(Guid id)
    {
        var user = new User
        {
            Id = id,
            Name = "Anton"
        };

        return Ok(user);
    }

    [EnableCors("CorsPolicy2")]
    [HttpPost]
    public ActionResult<IEnumerable<string>> Create(CreateUserRequest request)
    {
        return Ok();
    }

    [DisableCors]
    [HttpDelete]
    public ActionResult<IEnumerable<string>> Create(Guid id)
    {
        return NoContent();
    }
}

Enable CORS in Minimal APIs

To enable CORS for minimal API endpoints simply call RequireCors method for each endpoint:

app.MapGet("/api/books", () =>
{
    var books = SeedService.GetBooks(10);
    return Results.Ok(books);
}).RequireCors("AllowAllOrigins");

CORS Policy Options

We already learned what the CORS is and how to enable it in the ASP.NET Core.
It's time to explore what policy options does the CORS provide us:

  • Set the allowed origins
  • Set the allowed HTTP methods
  • Set the allowed request headers
  • Set the exposed response headers
  • Credentials in cross-origin requests

Allowed Origin

Specify what origins are allowed to access the resource.

builder.WithOrigins("http://example.com");

Allowed HTTP Methods

Define what HTTP methods can be used when accessing the resource.

builder.WithMethods("GET", "POST", "PUT", "DELETE", "PATCH");

Allowed Request Headers

Specify headers that can be used when making the request.

builder.WithHeaders("Content-Type", "Authorization");

Exposed Response Headers

Control which headers are exposed to the browser.

builder.WithExposedHeaders("X-Custom-Header");

Credentials in Cross-Origin Requests

Determine if cookies should be included with requests.

builder.AllowCredentials();

Allow Any Policy Options

There is a way to enable all policy options, for example for development:

if (builder.Environment.IsDevelopment())
{
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAllOrigins",
            policyBuilder => policyBuilder.AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin()
                //.AllowCredentials()
                .SetIsOriginAllowed(_ => true)
        );
    });   
}

// ...

if (app.Environment.IsDevelopment())
{
    app.UseCors("AllowAllOrigins");
}

NOTE: you can't use AllowAnyOrigin (wild card, allowing all origins) with AllowCredentials at the same time

Summary

Implementing CORS in ASP.NET Core is essential for modern web applications to securely manage cross-origin requests in the web browsers.
You can configure CORS for controllers and minimal APIs.
You can use CORS in development mode to simplify your frontend and backend development.
Use CORS in production mode only when it is absolutely required.

Hope you find this blog post useful. Happy coding!

Originally published at https://antondevtips.com.

After reading the post consider the following:

  • Subscribe to receive newsletters with the latest blog posts
  • Download the source code for this post from my github (available for my sponsors on BuyMeACoffee and Patreon)

If you like my contentโ€Šโ€”โ€Š consider supporting me

Unlock exclusive access to the source code from the blog posts by joining my Patreon and Buy Me A Coffee communities!

...



๐Ÿ“Œ Cross-Origin Resource Sharing (CORS) in ASP.NET Core: A Comprehensive Guide


๐Ÿ“ˆ 53.88 Punkte

๐Ÿ“Œ Visual Studio for Mac + ASP.NET Core โ€“ Getting started with ASP.NET Core using eShopOnWeb


๐Ÿ“ˆ 43.09 Punkte

๐Ÿ“Œ Microsoft .NET Maze: Understand .NET Core Vs .NET Framework Vs ASP.NET


๐Ÿ“ˆ 38.98 Punkte

๐Ÿ“Œ .NET Core, ASP.NET Core und Entity Framework Core 2.1 sind fertig


๐Ÿ“ˆ 38.98 Punkte

๐Ÿ“Œ what are competitive alternatives of .NET Core, ASP.NET Core, and EF Core for development/deployment on Linux?


๐Ÿ“ˆ 38.98 Punkte

๐Ÿ“Œ Microsoft ASP.NET Core 1.0/1.1 CORS Information Disclosure


๐Ÿ“ˆ 37.98 Punkte

๐Ÿ“Œ Microsoft ASP.NET Core 1.0/1.1 CORS information disclosure


๐Ÿ“ˆ 37.98 Punkte

๐Ÿ“Œ Leveraging Azure Cloud and Docker for ASP.NET Core Projects: A Comprehensive Guide for Businesses


๐Ÿ“ˆ 37.44 Punkte

๐Ÿ“Œ Using SkipToken for Paging in Asp.Net OData and Asp.Net Core OData


๐Ÿ“ˆ 37.28 Punkte

๐Ÿ“Œ Upcoming SameSite Cookie Changes in ASP.NET and ASP.NET Core


๐Ÿ“ˆ 37.28 Punkte

๐Ÿ“Œ Microsoft legt Bug-Bounty-Programm fรผr .NET Core und ASP.NET Core neu auf


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ Microsoft legt Bug-Bounty-Programm fรผr .NET Core und ASP.NET Core neu auf


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ Microsoft ASP.NET Core/.NET Core Web Request Spoofing [CVE-2017-0256]


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core 3.0 lรคuft nur noch auf .NET Core


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ .NET Core und ASP.NET Core 2.2.0 Preview 3 verfรผgbar


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core and Blazor updates in .NET Core 3.0 Preview 6


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ Microsoft ASP.NET Core/.NET Core Web Request erweiterte Rechte


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core and Blazor updates in .NET Core 3.0 Preview 7


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core and Blazor updates in .NET Core 3.0 Preview 8


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ 4021279 - Vulnerabilities in .NET Core, ASP.NET Core Could Allow Elevation of Privilege - Version: 1.1


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core and Blazor updates in .NET Core 3.0 Preview 9


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ Microsoft ASP.NET Core/.NET Core Web Request spoofing


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ Microsoft ASP.NET Core/.NET Core Web Request privilege escalation


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ Microsoft ASP.NET Core/.NET Core Web Request denial of service


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ Microsoft ASP.NET Core/.NET Core Web Request Denial of Service


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core and Blazor updates in .NET Core 3.0 Release Candidate 1


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core and Blazor updates in .NET Core 3.0


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core updates in .NET Core 3.1 Preview 2


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ Updating an ASP.NET Core 2.2 Web Site to .NET Core 3.1 LTS


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ Microsoft ASP.NET Core/.NET Core System.IO.Pipelines denial of service


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ Announcing a Microsoft .NET Core and ASP.NET Core Bug Bounty


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core updates in .NET Core 3.1 Preview 1


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core updates in .NET Core 3.1 Preview 3


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ ASP.NET Core updates in .NET Core 3.1


๐Ÿ“ˆ 33.17 Punkte

๐Ÿ“Œ rack-cors up to 0.4.0 CORS Request privilege escalation


๐Ÿ“ˆ 32.88 Punkte











matomo