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

Tel*_*ler 46 asp.net cookies xss httponly

灵感来自这篇CodingHorror文章" 保护你的Cookie:HttpOnly "

你怎么设置这个属性?在网络配置的某个地方?

小智 64

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

<httpCookies httpOnlyCookies="true"/>
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用。我尝试了“&lt;httpCookies httpOnlyCookies =“true”requireSSL =“true”/&gt;”,但两种设置都不起作用。 (2认同)

Dil*_*e-O 10

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

最重要的是,您只需在web.config中的system.web部分添加以下部分:

<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一下 - 不要实际使用domain ="String" - 设置一个有效的域或保留该属性. (8认同)

Por*_*man 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);
Run Code Online (Sandbox Code Playgroud)

在代码中执行此操作允许您有选择地选择哪些cookie是HttpOnly而哪些不是.