你究竟如何在ASP.NET中配置httpOnlyCookies?

时间:2008-08-28 22:14:17

标签: asp.net cookies xss httponly

受此CodingHorror文章的启发,“Protecting Your Cookies: HttpOnly

如何设置此属性?在网络配置的某个地方?

4 个答案:

答案 0 :(得分:58)

如果您使用的是ASP.NET 2.0或更高版本,则可以在Web.config文件中将其打开。在< system.web>中部分,添加以下行:

<httpCookies httpOnlyCookies="true"/>

答案 1 :(得分:10)

使用Rick的道具(在提到的博客文章中的第二条评论),这是httpOnlyCookies上的MSDN article

底线是您只需在web.config中的system.web部分添加以下部分:

<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />

答案 2 :(得分:8)

如果您想在代码中执行此操作,请使用System.Web.HttpCookie.HttpOnly属性。

这直接来自MSDN文档:

// Create a new HttpCookie.
HttpCookie myHttpCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// By default, the HttpOnly property is set to false 
// unless specified otherwise in configuration.
myHttpCookie.Name = "MyHttpCookie";
Response.AppendCookie(myHttpCookie);
// Show the name of the cookie.
Response.Write(myHttpCookie.Name);
// Create an HttpOnly cookie.
HttpCookie myHttpOnlyCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// Setting the HttpOnly value to true, makes
// this cookie accessible only to ASP.NET.
myHttpOnlyCookie.HttpOnly = true;
myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
Response.AppendCookie(myHttpOnlyCookie);
// Show the name of the HttpOnly cookie.
Response.Write(myHttpOnlyCookie.Name);

在代码中执行此操作可以选择性地选择哪些cookie是HttpOnly而哪些不是。

答案 3 :(得分:3)

有趣的是,将<httpCookies httpOnlyCookies="false"/>放在ASP.NET 2.0中似乎不会禁用httpOnlyCookies。请查看有关SessionID and Login Problems With ASP .NET 2.0

的文章

看起来微软决定不允许你从web.config中禁用它。请检查此post on forums.asp.net