C# 使服务器cookie安全
我一直在想如何在我们网站的所有服务器cookie上设置安全标志。我们正在运行.NET4.5。我尝试将C# 使服务器cookie安全,c#,asp.net,cookies,C#,Asp.net,Cookies,我一直在想如何在我们网站的所有服务器cookie上设置安全标志。我们正在运行.NET4.5。我尝试将添加到web.config文件中。我尝试添加。我尝试在代码中设置安全标志。没有任何效果。将以下c#函数添加到Global.asax.cs本应有效,但没有: protected void Application_EndRequest() { string authCookie = FormsAuthentication.FormsCookieName;
添加到web.config文件中。我尝试添加
。我尝试在代码中设置安全标志。没有任何效果。将以下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;
}
}
我有几个问题。首先,将其放入应用程序请求方法的逻辑是什么?第二,为什么我必须去掉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,
};
编辑-添加链接
另外,请查看答案以及如何配置web.config以确保cookie始终标记为安全的。通常在生成cookie时指定身份验证的cookie属性,该属性应在身份验证后立即出现。这是指定cookie是安全的适当位置。此外,您还应该使身份验证cookie仅限于http,否则它们可以在客户端访问,这不是您想要的。cookie已经是仅限于http的。这不是问题。我尝试使用以下几行生成cookie并同时设置其安全属性,但没有效果。已生成cookie,但未设置安全属性:
var cookie=FormsAuthentication.GetAuthCookie(user.UserName,false);cookie.Secure=true;System.Web.HttpContext.Current.Response.Cookies.Add(cookie)代码>谢谢。我试试看,奇怪。我试过你的代码,但没用。但是,我尝试添加到web.config,这次成功了。(我以前反复尝试过,但始终无法让它工作。)为了让事情变得更加混乱,我们正在使用表单身份验证,但我是否向该部分添加requireSSL=“true”似乎并不重要。为了安全起见,我还是要加上它。谢谢你的帮助。