HttpCookie.HttpOnly Свойство

Определение

Получает или задает значение, указывающее имеет ли клиентский скрипт доступ к файлу Cookie.

public:
 property bool HttpOnly { bool get(); void set(bool value); };
public bool HttpOnly { get; set; }
member this.HttpOnly : bool with get, set
Public Property HttpOnly As Boolean

Значение свойства

Значение true, если файл Cookie содержит атрибут HttpOnly, и клиентский скрипт не имеет к нему доступ; в противном случае — false. Значение по умолчанию — false.

Примеры

В следующем примере кода показано, как создать HttpOnly файл cookie, и показано, как он недоступен клиенту через ECMAScript.

<%@ 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>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    
    ' Create a new HttpCookie.
    Dim myHttpCookie As 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.
    Dim myHttpOnlyCookie As 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)

  End Sub
  
</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>

Комментарии

Майкрософт Internet Explorer версии 6 с пакетом обновления 1 (SP1) и более поздних версий поддерживает свойство cookie , HttpOnlyкоторое может помочь устранить угрозы меж site-scripting, которые приводят к краже файлов cookie. Украденные файлы cookie могут содержать конфиденциальную информацию, идентифицирующие пользователя на сайте, например идентификатор сеанса ASP.NET или запрос на проверку подлинности на основе форм, и могут быть воспроизведены злоумышленником, чтобы замаскироваться под пользователя или получить конфиденциальную информацию. HttpOnly Когда файл cookie получен соответствующим браузером, он становится недоступным для клиентского скрипта.

Внимание!

Если задать HttpOnly для свойства значение true , злоумышленник с доступом к сетевому каналу не будет напрямую обращаться к файлу cookie. Рассмотрите возможность использования протокола SSL для защиты от этого. Безопасность рабочей станции также важна, так как злоумышленник может использовать открытое окно браузера или компьютер, содержащий постоянные файлы cookie, для получения доступа к веб-сайту с допустимым удостоверением пользователя.

Применяется к