HttpCookie.HttpOnly 属性

HttpCookie.HttpOnly 属性

.NET Framework 4.5
 
其余版本
 
此主题还没有评级 评价此主题
 

 

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

 

命名空间:   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,则客户端脚本不能对它进行访问。html

警告说明警告

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

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

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

C#
VB
 
<%@ 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>

相关文章
相关标签/搜索