【发布时间】: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);