【问题标题】:Making server cookies secure使服务器 cookie 安全
【发布时间】:2015-11-20 21:45:41
【问题描述】:

我一直在试图弄清楚如何在我们网站的所有服务器 cookie 上设置安全标志。我们正在运行 .NET 4.5。我尝试将<httpCookies requireSSL="true" /> 添加到 web.config 文件中。我尝试添加<authentication><forms requireSSL="true" /></authentication>。我尝试在代码中设置安全标志。没有任何效果。将以下 c# 函数添加到 Global.asax.cs 应该可以工作,但没有:

    protected void Application_EndRequest()
    {
        string authCookie = FormsAuthentication.FormsCookieName;

        foreach (string sCookie in Response.Cookies)
        {
            if (sCookie.Equals(authCookie))
            {
                // Set the cookie to be secure. Browsers will send the cookie
                // only to pages requested with https
                var httpCookie = Response.Cookies[sCookie];
                if (httpCookie != null) httpCookie.Secure = true;
            }

    }

在我摆脱“if (sCookie.Equals(authCookie))...”语句后,它终于开始工作了。所以这是工作版本:

    protected void Application_EndRequest()
    {
        string authCookie = FormsAuthentication.FormsCookieName;

        foreach (string sCookie in Response.Cookies)
        {
            // Set the cookie to be secure. Browsers will send the cookie
            // only to pages requested with https
            var httpCookie = Response.Cookies[sCookie];
            if (httpCookie != null) httpCookie.Secure = true;
        }
    }

我有几个问题。首先,将其放入 Application_EndRequest 方法背后的逻辑是什么?其次,为什么我必须摆脱 sCookie.Equals(authCookie)) 部分?最后,有没有人找到更优雅的解决方案?谢谢。

【问题讨论】:

  • 通常在生成 cookie 时指定身份验证的 cookie 属性,该 cookie 应在身份验证后立即发生。这是指定 cookie 是安全的适当位置。此外,您还应该仅将身份验证 cookie 设为 http,否则它们可以在客户端访问,这不是您想要的。
  • cookies 已经是 http 的了。这不是问题。我尝试使用以下几行来生成 cookie 并同时设置其安全属性,但没有任何效果。 cookie 已生成,但未设置安全属性:var cookie = FormsAuthentication.GetAuthCookie(user.UserName, false); cookie.Secure = true; System.Web.HttpContext.Current.Response.Cookies.Add(cookie);

标签: c# asp.net cookies


【解决方案1】:

如果您通过 HTTP 而不是 HTTPS 执行请求,那么我认为您不能设置 Secure = true。您能否验证您正在通过安全连接运行?如果您在开发盒上进行测试,您可以对如何生成本地证书进行一些 google / bing 搜索。也不要忘记加密您的 cookie,使其在客户端不可读。

这是一些示例代码。

var userName = "userName";
var expiration = DateTime.Now.AddHours(3);
var rememberMe = true;
var ticketValueAsString = generateAdditionalTicketInfo(); // get additional data to include in the ticket

var ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, expiration, rememberMe, ticketValueAsString);
var encryptedTicket = FormsAuthentication.Encrypt(ticket); // encrypt the ticket

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
    {
        HttpOnly = true,
        Secure = true,
    };

编辑 - 添加链接

还请查看this previous 答案以及如何配置 web.config 以确保 cookie 始终标记为安全。

【讨论】:

  • 谢谢。我会试试的。
  • 奇怪。我试过你的代码,它没有用。但是,我尝试将 添加到 web.config 并且这次它起作用了。 (我之前曾多次尝试过,但始终无法正常工作。)为了让事情更加混乱,我们正在使用表单身份验证,但我是否将 requireSSL="true" 添加到该部分或添加到该部分似乎并不重要不是。无论如何,为了安全起见,我还是要添加它。感谢您的帮助。
猜你喜欢
  • 2012-05-21
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多