如何保护ASP.NET_SessionId cookie?

我已经将.ASPXAUTH cookie设置为https,但是我不确定如何有效地对ASP.NET_SessionId执行相同的操作。

整个站点使用HTTPS,因此不需要cookie同时处理http和https。

以下是Anubhav Goyal撰写的博客文章中的一段代码:

// this code will mark the forms authentication cookie and the // session cookie as Secure. if (Response.Cookies.Count > 0) { foreach (string s in Response.Cookies.AllKeys) { if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid") { Response.Cookies[s].Secure = true; } } } 

将此添加到global.asax中的EndRequest事件处理程序应该使所有页面调用都发生这种情况。

注意:build议编辑添加一个break; 声明在一个成功的“安全”的任务。 我拒绝了这个编辑,因为它只允许一个cookie被强制保护,而第二个会被忽略。 增加一个计数器或其他一些度量标准来确定两者在这一点上已经被确保和中断是不可想象的。 然而,用更新的代码技术,这可能会写得更好:

 Response.Cookies[FormsAuthentication.FormsCookieName]?.Secure = true; Response.Cookies["asp.net_sessionid"]?.Secure = true; 

添加; secure ; secure后缀到Set-Cookie http头我简单地使用web.config中的<httpCookies>元素:

 <system.web> <httpCookies httpOnlyCookies="true" requireSSL="true" /> <system.web> 

恕我直言,比在Anubhav Goyal的文章编写代码更方便。

请参阅: http : //msdn.microsoft.com/en-us/library/ms228262(v=vs.100).aspx

与上面的Marcel解决scheme一起来保护Forms Authentication cookie,你还应该更新“authentication”configuration元素来使用SSL

 <authentication mode="Forms"> <forms ... requireSSL="true" /> </authentication> 

其他明智的authenticationcookie不会是https

请参阅: http : //msdn.microsoft.com/en-us/library/vstudio/1d3t3c61(v=vs.100).aspx

发现在Session_Start中设置安全属性已经足够了,正如在MSDN博客“ 确保会话ID:ASP / ASP.NET ”中所推荐的那样。

  protected void Session_Start(Object sender, EventArgs e) { SessionStateSection sessionState = (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState"); string sidCookieName = sessionState.CookieName; if (Request.Cookies[sidCookieName] != null) { HttpCookie sidCookie = Response.Cookies[sidCookieName]; sidCookie.Value = Session.SessionID; sidCookie.HttpOnly = true; sidCookie.Secure = true; sidCookie.Path = "/"; } } 

如果整个站点使用HTTPS,那么sessionId cookie至less与HTTPSencryption一样安全。 这是因为cookie是作为HTTP标题发送的,使用SSL时,HTTP标题在传输时使用SSLencryption。