Reputation: 1638
For testing purposes, two web apps are set up, a "client" app (localhost) and a server app (Azure web app). The client sends an AJAX request to the server and receives a cookie in response. Then it makes another AJAX call to the server, but there's no cookie in the request, it's missing.
Here's the server configuration (CORS setup; https://localhost:44316 is my "client" URL):
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => {
o.AddPolicy("policy1", builder =>
builder.WithOrigins("https://localhost:44316")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("policy1");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Here's the first controller, returning the cookie:
[Route("api/[controller]")]
[ApiController]
public class AController : ControllerBase
{
[HttpPost]
public IActionResult Post()
{
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Expires = DateTime.Now.AddMinutes(10),
SameSite = SameSiteMode.None
};
Response.Cookies.Append("mykey", "myvalue", cookieOptions);
return Ok();
}
}
Here's the second controller, which should receive the cookie (but it doesn't):
[Route("api/[controller]")]
[ApiController]
public class BController : ControllerBase
{
[HttpPost]
public IActionResult Post()
{
var x = Request.Cookies;
return Ok(JsonConvert.SerializeObject(x));
}
}
And here's the calling script from the "client" (first and second call, respectively):
function Go()
{
$.ajax({
url: 'https://somewebsite.azurewebsites.net/api/a',
type: 'post',
xhrFields: {
withCredentials: true
},
success: function (data, textStatus, jQxhr)
{
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown)
{
console.log(errorThrown);
}
});
}
function Go2()
{
$.ajax({
url: 'https://somewebsite.azurewebsites.net/api/b',
type: 'post',
xhrFields: {
withCredentials: true
},
success: function (data, textStatus, jQxhr)
{
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown)
{
console.log(errorThrown);
}
});
}
Does anyone have an idea what could be the problem here?
Upvotes: 3
Views: 2278
Reputation: 29301
I quite like the style of what you are doing here in terms of an SPA getting cookies from an API. Some recommendations below, based on experience at dealing with these issues.
PROBLEM
You are calling from the browser to an API in a different domain, meaning the cookie is third party and modern browsers will drop it aggressively.
SameSite=None
is the theoretical solution from standards docs but these often do not explain current browser behaviour:
Secure
property, as Jason Pan saysSOLUTION
The preferred option is to design hosting domains so that only first party
cookies are used, and many software companies have done this. It can be done by running the API in a child or sibling domain of the web origin:
On a developer PC you can do this simply by updating your hosts file. Note also that you can run web and API components on different ports and they will remain same site:
127.0.0.1 localhost www.example.com api.example.com
:1 localhost
The browser will then still be making CORS requests, but will consider the cookie issued by the API to be in the same site as the web origin. You can then also change the cookie settings to use SameSite=strict
, for best security.
FURTHER INFO
At Curity we have published some recent articles on web security that are closely related to your question, since secure cookies used in OpenID Connect security have also had to deal with dropped cookie problems:
Upvotes: 1
Reputation: 16076
As this document said :
Cookies that assert SameSite=None must also be marked as Secure
But you didn't, so use this instead:
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Expires = DateTime.Now.AddMinutes(10),
SameSite = SameSiteMode.None,
Secure = true
};
And this is my test result:
Upvotes: 3
Reputation: 22099
You should know AddTransient
, AddScoped
and AddSingleton first. Below post will useful to you.
AddTransient, AddScoped and AddSingleton Services Differences
And you need use AddSingleton
, and you will get the cookie value by key.
Offical blogs: How to work with cookies in ASP.NET Core
It works for me, you can find sample code in the blogs I provided.
1. test code
2. test result in another controller.
Upvotes: 0