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>

相關文章
相關標籤/搜索