When developing a React web application that interacts with a server via a Web API, I encountered an issue where the browser does not store cookies with the SameSite=None attribute.
My React application, running at https://localhost:3000
, sends POST requests to an API server at https://localhost:7000
. The server responds with a Set-Cookie header, attempting to set a cookie with the attributes SameSite=None
; Secure. However, despite the presence of this header in the response, the browser does not store the cookie, and subsequent requests lack the necessary authentication data.
If I use the same domain, the cookies are stored.
I tried:
fetch('https://localhost:7000/api/login', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: 'user', password: 'password' })
})
.then(response => {
// Handle response
});
aspnet:
//Cookies
cookies.Append("AccessToken", accessToken, new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.None,
Expires = DateTimeOffset.UtcNow.AddMinutes(15)
});
cookies.Append("RefreshToken", refreshToken, new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.None,
Expires = DateTimeOffset.UtcNow.AddDays(7)
});
//Cors
public static IServiceCollection AddAppCors(this IServiceCollection services)
{
return services.AddCors(options =>
{
options.AddPolicy(CorsPolicies.Base, policy =>
{
policy.WithOrigins("https://localhost:3000")
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
//Program.cs
...
builder.Services.AddAppCors(); //ADD MY CORS
...
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(CorsPolicies.Base); //USE MY CORS
app.UseAuthentication();
app.UseJwtSecurityStampValidation();
app.UseAuthorization();
app.MapControllers();
app.Run();