【问题标题】:What might cause a cookie to not get set in the browser when there is a Set-Cookie header in the response?当响应中有 Set-Cookie 标头时,什么可能导致 cookie 未在浏览器中设置?
【发布时间】:2019-01-26 16:26:04
【问题描述】:

我正在开发一个使用 cookie 进行表单身份验证的 .net 网站,我想添加另一个安全 cookie 来保存访问和刷新令牌。 cookie 被添加到Response.Cookies,一切似乎都很好。我使用 fiddler 检查响应标头以确保设置了 Set-Cookie 标头。

HTTP/1.1 302 Found
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Location: /
Set-Cookie: 
    TestTokenCookie=(truncated for brevity); 
    domain=local.foobar.com; 
    expires=Sun, 18-Nov-2018 14:42:56 GMT;
    path=/
X-Frame-Options: SAMEORIGIN
X-UA-Compatible: IE=Edge,chrome=1
Date: Mon, 20 Aug 2018 13:42:59 GMT
Content-Length: 118

响应看起来正确,但浏览器中没有显示它的 cookie。我正在使用 Edit This Cookie chrome 扩展来查看已设置的 cookie。这是我使用的设置cookie的代码。

public void CreateTokenCookie(TokenCookieData tokenCookieData, HttpContextBase currentContext, bool createPersistentTicket = true)
{
    var ticket = new FormsAuthenticationTicket(1,
        tokenCookieData.Username,
        DateTime.Now,
        DateTime.Now.AddDays(90),
        createPersistentTicket,
        tokenCookieData.ToString());

    CreateCookieFromTicket(ticket, TOKEN_COOKIE_NAME, true, currentContext);
}

private void CreateCookieFromTicket(FormsAuthenticationTicket ticket, string cookieName, bool httpOnly, HttpContextBase currentContext)
{
    var encryptedTicket = FormsAuthentication.Encrypt(ticket);

    var cookie = new HttpCookie(cookieName, encryptedTicket)
    {
        HttpOnly = httpOnly,
        Secure = FormsAuthentication.RequireSSL,
        Path = FormsAuthentication.FormsCookiePath,
        Expires = ticket.Expiration
    };

    var domain = GetCookieDomain();

    if (domain != null)
    {
        cookie.Domain = domain;
    }

    if (currentContext.Response.Cookies[cookieName] != null)
    {
        currentContext.Response.Cookies.Remove(cookieName);
    }

    currentContext.Response.Cookies.Add(cookie);
}

知道为什么没有在浏览器中设置 cookie 吗?

【问题讨论】:

    标签: c# google-chrome cookies


    【解决方案1】:

    我认为问题可能出在您的域名“domain=local.test.com;”

    查看https://stackoverflow.com/a/24071239/10241547了解更多详情

    test.com 似乎是该限制列表的一部分

    或者可能是com

    // com : https://en.wikipedia.org/wiki/.com
    com
    

    见:https://publicsuffix.org/list/public_suffix_list.dat

    【讨论】:

    • 我没有在列表中看到 test.com,只是 test.ru 也 test 只是一个占位符
    【解决方案2】:

    我认为问题最终出在 cookie 值的长度上。原始值最终约为 4105 个字符,超过了 cookie 的最大大小 4093 字节。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-24
      • 2018-10-26
      • 2012-05-02
      • 2019-04-26
      • 2023-03-25
      • 1970-01-01
      • 2020-10-07
      • 2015-09-12
      相关资源
      最近更新 更多