我一直在试图找出如何在我们网站的所有服务器cookie上设置安全标志。我们正在运行。net 4.5。我试着把<httpCookies requireSSL="true" />
添加到网络上。配置文件。我试着加入<authentication><forms requireSSL="true" /></authentication>
。我试过在代码中设置安全标志。没有任何效果。在Global.asax.cs中添加以下c#函数应该可以工作,但是没有:
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))部分?最后,有人找到更优雅的解决方案了吗?谢谢。
如果您通过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,
};
EDIT -添加链接
还可以看看前面的答案以及如何配置您的web。配置以确保cookie始终被标记为安全