HttpCookie.HttpOnly Propiedad

Definición

Obtiene o establece un valor que especifica si se puede obtener acceso a una cookie mediante script de cliente.

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

Valor de propiedad

Boolean

Es true si la cookie tiene el atributo HttpOnly y no se puede obtener acceso a la misma a través de un script de cliente; de lo contrario, es false. De manera predeterminada, es false.

Ejemplos

En el ejemplo de código siguiente se muestra cómo escribir una HttpOnly cookie y se muestra cómo no es accesible por el cliente a través de 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>

Comentarios

Microsoft Internet Explorer versión 6 Service Pack 1 y versiones posteriores admiten una propiedad cookie, HttpOnly, que puede ayudar a mitigar las amenazas de scripting entre sitios que dan lugar a cookies robadas. Las cookies robadas pueden contener información confidencial que identifica al usuario en el sitio, como el identificador de sesión de ASP.NET o el vale de autenticación de formularios, y el atacante puede reproducirlo para enmascarar como usuario o obtener información confidencial. Cuando un explorador compatible recibe una HttpOnly cookie, no es accesible para el script del lado cliente.

Precaución

Establecer la HttpOnly propiedad true en no impide que un atacante tenga acceso al canal de red acceda directamente a la cookie. Considere la posibilidad de usar capa de sockets seguros (SSL) para ayudar a protegerse frente a esto. La seguridad de la estación de trabajo también es importante, ya que un usuario malintencionado podría usar una ventana abierta del explorador o un equipo que contenga cookies persistentes para obtener acceso a un sitio web con la identidad de un usuario legítimo.

Se aplica a