HttpCookie.HttpOnly 属性

HttpCookie.HttpOnly 属性

.NET Framework 4.5
 
其他版本
 
此主题尚未评级 评价此主题
 

获取或设置一个值,该值指定 Cookie 是否可通过客户端脚本访问。

命名空间:  System.Web
程序集:  System.Web(在 System.Web.dll 中)
 
public bool HttpOnly { get; set; }

属性值

类型:System.Boolean
如果 Cookie 具有 HttpOnly 特性且不能通过客户端脚本访问,则为 true;否则为 false 默认值为 false 

Microsoft Internet Explorer 版本 6 Service Pack 1 和更高版本支持 Cookie 属性 HttpOnly,该属性有助于缓解跨站点脚本威胁,这种威胁可能导致 Cookie 被窃取。 窃取的 Cookie 可以包含标识站点用户的敏感信息,如 ASP.NET 会话 ID 或 Forms 身份验证票证,攻击者可以重播窃取的 Cookie,以便伪装成用户或获取敏感信息。 如果兼容浏览器接收到 HttpOnly Cookie,则客户端脚本不能对它进行访问。

警告说明警告

将 HttpOnly 属性设置为 true,并不能防止对网络频道具有访问权限的攻击者直接访问该 Cookie。 针对这种情况,应考虑使用安全套接字层 (SSL) 来提供帮助。 工作站的安全也很重要,原因是恶意用户可能使用打开的浏览器窗口或包含持久性 Cookie 的计算机,以合法用户的标识获取对网站的访问。

有关可能发生的攻击以及如何使用此属性缓解攻击的更多信息,请参见 Mitigating Cross-site Scripting With HTTP-only Cookies(使用仅用于 HTTP 的 Cookies 缓解跨站点脚本)。

下面的代码示例演示如何编写 HttpOnly Cookie,并演示客户端为何不能通过 ECMAScript 访问该 Cookie。

 
<%@ Page Language="C#" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load(object sender, EventArgs e)
    {
        // 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);
    }
</script>


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
<script type="text/javascript">
function getCookie(NameOfCookie)
{
    if (document.cookie.length > 0) 
{ 
    begin = document.cookie.indexOf(NameOfCookie+"="); 
    if (begin != -1)
   { 
    begin += NameOfCookie.length+1; 
      end = document.cookie.indexOf(";", begin);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(begin, end));       
      } 
  }
return null;  
}
</script>

<script type="text/javascript">

    // This code returns the cookie name.
    alert("Getting HTTP Cookie");
    alert(getCookie("MyHttpCookie"));

    // Because the cookie is set to HttpOnly,
    // this returns null.
    alert("Getting HTTP Only Cookie");
    alert(getCookie("MyHttpOnlyCookie"));

</script> 


</body>
</html>

原文地址:https://www.cnblogs.com/xgbzsc/p/3445673.html