我一直试图找出如何在我们网站的所有服务器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;
}
}
在我摆脱了&#34; if(sCookie.Equals(authCookie))后,它终于开始工作......&#34;声明。所以这是工作版本:
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))部分?最后,有没有人找到更优雅的解决方案?感谢。
答案 0 :(得分:0)
如果您通过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始终标记为安全。