MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

Set-Cookie

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

 
La cabecera de respuesta HTTP Set-Cookie se usa para enviar cookies desde el servidor al agente de usuario.
 
Para más información, visite la guía sobre cookies HTTP.
 
Tipo de cabecera Response header
Forbidden header name no

Sintaxis

Set-Cookie: <cookie-name>=<cookie-value> 
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<non-zero-digit>
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>
Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>
Set-Cookie: <cookie-name>=<cookie-value>; Secure
Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly

Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Strict
Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Lax

// Es posible usar múltiples directivas, por ejemplo:
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly

Directivas

<cookie-name>=<cookie-value>
Una cookie comienza con un par nombre-valor:
  • Un <cookie-name> puede ser cualquier cosa excepto caracteres de control (CTLs) o espacios y tabulaciones. Tampoco debe contener caracteres de separación como los siguientes: ( ) < > @ , ; : \ " /  [ ] ? = { }.
  • Un <cookie-value> opcionalmente puede ser establecido dentro de comillas dobles y se permite usar cualquier caracter US-ASCII excluyendo CTLs, espacios en blanco, comillas dobles, comas, punto y coma y la barra invertida. Codificación: Muchas implementaciones realizan codificación de URL sobre los valores de la cookie, aunque esto no es requerido por la especificación RFC. Esto ayuda a satisfacer los requerimientos sobre los caracteres permitidos para <cookie-value>.
  • Prefijo __Secure-: Las cookies cuyo nombre comience por __Secure- (los guiones forman parte del prefijo) deben ser establecidas con la bandera secure y deben provenir de una página segura (HTTPS).
  • Prefijo __Host-: Las cookies cuyo nombre comience por __Host- deben ser establecidas con la bandera secure, provenir de una página segura (HTTPS), no deben tener especificado un dominio (y por tanto no son enviadas a subdominios) y la ruta debe ser "/".
Expires=<date> Optional

The maximum lifetime of the cookie as an HTTP-date timestamp. See Date for the detailed format. If not specified, the cookie will have the lifetime of a session cookie. A session is finished when the client is shut down meaning that session cookies will get removed at that point. However, many web browsers have a feature called session restore that will save all your tabs and have them come back next time you use the browser. Cookies will also be present and it's like you had never actually closed the browser.

Max-Age=<non-zero-digit> Optional
Number of seconds until the cookie expires. One or more digits 1 through 9. Older browsers (ie6, ie7, and ie8) do not support max-age. For other browsers, if both (Expires and Max-Age) are set, Max-Age will have precedence.
Domain=<domain-value> Optional
Specifies those hosts to which the cookie will be sent. If not specified, defaults to the host portion of the current document location (but not including subdomains). Contrary to earlier specifications, leading dots in domain names are ignored. If a domain is specified, subdomains are always included.
Path=<path-value> Optional
Indicates a URL path that must exist in the requested resource before sending the Cookie header. The %x2F ("/") character is interpreted as a directory separator and sub directories will be matched as well (e.g. path=/docs, "/docs", "/docs/Web/", or "/docs/Web/HTTP" will all be matched).
Secure Optional
A secure cookie will only be sent to the server when a request is made using SSL and the HTTPS protocol. However, confidential or sensitive information should never be stored or transmitted in HTTP Cookies as the entire mechanism is inherently insecure and this doesn't mean that any information is encrypted, for example.

Note: Insecure sites (http:) can't set cookies with the "secure" directive anymore (new in Chrome 52+ and Firefox 52+).

HttpOnly Optional
HTTP-only cookies aren't accessible via JavaScript through the Document.cookie property, the XMLHttpRequest and Request APIs to mitigate attacks against cross-site scripting (XSS).
SameSite=Strict
SameSite=Lax Optional 

Allows servers to assert that a cookie ought not to be sent along with cross-site requests, which provides some protection against cross-site request forgery attacks (CSRF).

Examples

Session cookies will get removed when the client is shut down. They don't specify the Expires or Max-Age directives. Note that web browser have often enabled session restoring.

Set-Cookie: sessionid=38afes7a8; httponly; Path=/

Instead of expiring when the client is closed, permanent cookies expire at a specific date (Expires) or after a specific length of time (Max-Age).

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly

Invalid domains

A cookie belonging to a domain that does not include the origin server should be rejected by the user agent. The following cookie will be rejected if it was set by a server hosted on originalcompany.com.

Set-Cookie: qwerty=219ffwef9w0f; Domain=somecompany.co.uk; Path=/; Expires=Wed, 30 Aug 2019 00:00:00 GMT

Cookies names with the prefixes __Secure- and __Host- can be used only if they are set with the secure directive from a secure (HTTPS) origin. In addition, cookies with the __Host- prefix must have a path of "/" (the entire host) and must not have a domain attribute. For clients that don't implement cookie prefixes, you cannot count on having these additional assurances and the cookies will always be accepted.

// Both accepted when from a secure origin (HTTPS)
Set-Cookie: __Secure-ID=123; Secure; Domain=example.com
Set-Cookie: __Host-ID=123; Secure; Path=/

// Rejected due to missing Secure directive
Set-Cookie: __Secure-id=1

// Rejected due to the missing Path=/ directive (unless at root of the site)
Set-Cookie: __Host-id=1; Secure

// Rejected due to setting a domain
Set-Cookie: __Host-id=1; Secure; Path=/; domain=example.com

Specifications

Specification Title
RFC 6265, section 4.1: Set-Cookie HTTP State Management Mechanism
RFC draft-ietf-httpbis-cookie-prefixes-00 Cookie Prefixes
RFC draft-ietf-httpbis-cookie-same-site-00 Same-Site Cookies
RFC draft-ietf-httpbis-cookie-alone-01 Strict Secure Cookies

Browser compatibility

Feature Chrome Edge Firefox Internet Explorer Opera Safari Servo
Soporte básico(Si)(Si)(Si)(Si)(Si)(Si)?
Max-Age(Si)(Si)(Si)8.0(Si)(Si)?
HttpOnly1.0(Si)3.09.0115.0?
Cookie prefixes49(Si)50?36(Si)?
SameSite51Sin soporteSin soporte1Sin soporte39Sin soporte?
Feature Android Chrome for Android Edge Mobile Firefox for Android IE Mobile Opera Mobile Safari Mobile
Soporte básico(Si)(Si)(Si)(Si)(Si)(Si)(Si)
Max-Age(Si)(Si)(Si)(Si)(Si)(Si)(Si)
HttpOnly?(Si)(Si)1.0(Si)(Si)iOS 4
Cookie prefixes?49(Si)50?36(Si)
SameSite5151Sin soporteSin soporte1Sin soporte39Sin soporte

1. See Bugzilla bug 795346.

Compatibility notes

  • Starting with Chrome 52 and Firefox 52, insecure sites (http:) can't set cookies with the "secure" directive anymore.

See also

Etiquetas y colaboradores del documento

 Colaboradores en esta página: garolard
 Última actualización por: garolard,