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 frontend and backend 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 JavaScript frontend and backend servers are hosted on different origins, then you will need to configure CORS to allow your JavaScript frontend to make requests to your backend servers.
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("<replace_with_your_frontend_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();
Frontend Configuration
When making requests from your JavaScript frontend to your backend, 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 JavaScript frontend can send requests to your backend server across different origins.
Updated 14 days ago
Next let's test the authentication flows to ensure that sessions are properly being managed.