Configure CORS
Your application might need to configure Cross-Origin Resource Sharing (CORS).
Determine If You Actually Need CORS
CORS is only required when your frontend and backend are on different domains or ports.
If you're hosting both your React app and C# server under the same domain (e.g., both on
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 web pages can request resources from different domains. If your React frontend and C# server are hosted on different domains or ports, then you will need to configure CORS to allow React to make requests to C#.
ASP.NET Core CORS Configuration
First, add the CORS services to the dependency injection container in your Program.cs
file and configure C# to use CORS:
// Program.cs
using Microsoft.AspNetCore.Cors;
builder.Services.AddCors(options =>
{
options.AddPolicy("MyAllowedOrigins",
policy =>
{
policy.WithOrigins("http://localhost:3000") // Replace value with whatever your React domain/port is.
.AllowAnyHeader()
.AllowAnyMethod();
});
});
...
Then, enable CORS in the middleware pipeline (before UseRouting
and after any middleware that might return responses):
// For the default policy
app.UseCors();
// Or for a named policy
app.UseCors("MyAllowedOrigins");
React Configuration
When making requests from React to C#, ensure you include the credentials configuration in your AJAX client.
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, // <-- this
});
Fetch
fetch('http://localhost:8080/api/endpoint', {
credentials: 'include'
})
Your React app can now make authenticated requests to your C# server across different origins.
Updated 8 days ago
Now let's test the full authentication flow from end-to-end.