*I know there are several questions regarding deleting a cookie here. I'm asking why I can't delete 2 cookies with the same key and value.
I'm working on a web application that has tons of legacy code, and in some cases, clients receive 2 cookies with the same key, value but the domain is different: one is explicit and the other is not (with and without dot notation aka .domain.com
, domain.com
). I need to delete both of those cookies.
Only one of the cookies is being deleted. The cookie is set from an ASP.NET application and the (.net core 2.1) API re-uses it. The API is a subdomain of the ASP.NET application, and the UI part is another subdomain.
- What eventually worked for me, is deleting all of the cookies:
private void DeleteCookiesOnUnauthorizedResponse(HttpContext context)
{
var domain = new Uri(SOME_ENV_VARIABLE).Host;
var options = GenerateExpiredCookieOptions(domain);
var optionsWithDot = GenerateExpiredCookieOptions('.' + domain);
var cookieList = context.Request.Cookies.ToList();
foreach (var cookie in cookieList)
{
context.Response.Cookies.Delete(cookie.Key, options);
context.Response.Cookies.Delete(cookie.Key, optionsWithDot);
}
}
private CookieOptions GenerateExpiredCookieOptions(string domain)
{
return new CookieOptions
{
Domain = domain,
Expires = DateTime.Now.AddMonths(-2),
IsEssential = true,
HttpOnly = true,
Secure = true,
Path = "/",
SameSite = SameSiteMode.Lax,
};
}
context.Response.Cookies.Append(someKey, string.Empty, optionsWithExpiredDate);
context.Response.Cookies.Delete(someKey);
Using a loop to delete only what I need didn't work either:
foreach (var cookie in cookieList)
{
if(cookie.key == "myKey"){
context.Response.Cookies.Delete(cookie.Key, options);
context.Response.Cookies.Delete(cookie.Key, optionsWithDot);
}
}
Both of the cookies were sent to the browser as seen in the network tab, but only one of them got deleted.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…