Configure Cross-Origin Resource Sharing (CORS)

If your frontend and backend are hosted on different origins you'll need to configure CORS.

⚠️

Determine If You Actually Need CORS

CORS is only required when your frontend and backend are hosted on different origins. To be considered the same origin, the scheme, domain and port of the frontend and backend must be the same. For example, if you're hosting both your React app and C# server under origin https://example.com, you don't need to configure CORS and can skip to Testing Login and Logout Flows.

Cross-Origin Resource Sharing (CORS) is a security feature that controls how browsers can request resources from different domains. If your React frontend and C# server are hosted on a different origin, then you will need to configure CORS to allow your React frontend to make requests to your C# server.


ASP.NET CORS Configuration

First, add the CORS service to the dependency injection container in your Program.cs file:

// Program.cs

using Microsoft.AspNetCore.Cors;

builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy",
        policy =>
        {
            policy.WithOrigins("http://localhost:3000") // Replace value with your React origin.
                  .AllowAnyHeader()
                  .AllowAnyMethod()
                  .AllowCredentials();
        });
});

...

Then, enable CORS in the middleware pipeline. Note, the CORS middleware should be enabled after app.UseRouting() but before app.UseAuthentication();.

app.UseRouting();

// Enable the CORS policy to be applied to all endpoints.  
app.UseCors("CorsPolicy");

app.UseAuthentication();



React Configuration

When making requests from React to C#, ensure you enable credentials to be sent in the request. If credentials aren't enabled, then the session cookie won't be sent in the request.

Axios

axios.defaults.withCredentials = true;

// ...or...

const apiClient = axios.create({
  baseURL: `http://localhost:8080/api`,
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
  withCredentials: true, // Enable credentials to be sent.
});

Fetch

fetch('http://localhost:8080/api/endpoint', {
  credentials: 'include'
})

Now that CORS is configured, your React frontend can send requests to your C# server across different origins.


What’s Next

Next let's test the authentication flows to ensure that sessions are properly being managed.