Куки, document.cookie
Куки – это небольшие строки данных, которые хранятся непосредственно в браузере. Они являются частью HTTP-протокола, определённого в спецификации RFC 6265.
Куки обычно устанавливаются веб-сервером при помощи заголовка Set-Cookie . Затем браузер будет автоматически добавлять их в (почти) каждый запрос на тот же домен при помощи заголовка Cookie .
Один из наиболее частых случаев использования куки – это аутентификация:
- При входе на сайт сервер отсылает в ответ HTTP-заголовок Set-Cookie для того, чтобы установить куки со специальным уникальным идентификатором сессии («session identifier»).
- Во время следующего запроса к этому же домену браузер посылает на сервер HTTP-заголовок Cookie .
- Таким образом, сервер понимает, кто сделал запрос.
Мы также можем получить доступ к куки непосредственно из браузера, используя свойство document.cookie .
Куки имеют множество особенностей и тонкостей в использовании, и в этой главе мы подробно с ними разберёмся.
Чтение из document.cookie
Хранит ли ваш браузер какие-то куки с этого сайта? Посмотрим:
Значение document.cookie состоит из пар ключ=значение , разделённых ; . Каждая пара представляет собой отдельное куки.
Чтобы найти определённое куки, достаточно разбить строку из document.cookie по ; , и затем найти нужный ключ. Для этого мы можем использовать как регулярные выражения, так и функции для обработки массивов.
Оставим эту задачу читателю для самостоятельного выполнения. Кроме того, в конце этой главы вы найдёте полезные функции для работы с куки.
Запись в document.cookie
Мы можем писать в document.cookie . Но это не просто свойство данных, а акcессор (геттер/сеттер). Присваивание к нему обрабатывается особым образом.
Запись в document.cookie обновит только упомянутые в ней куки, но при этом не затронет все остальные.
Например, этот вызов установит куки с именем user и значением John :
Если вы запустите этот код, то, скорее всего, увидите множество куки. Это происходит, потому что операция document.cookie= перезапишет не все куки, а лишь куки с вышеупомянутым именем user .
Технически, и имя и значение куки могут состоять из любых символов, для правильного форматирования следует использовать встроенную функцию encodeURIComponent :
Существует несколько ограничений:
- После encodeURIComponent пара name=value не должна занимать более 4Кб. Таким образом, мы не можем хранить в куки большие данные.
- Общее количество куки на один домен ограничивается примерно 20+. Точное ограничение зависит от конкретного браузера.
У куки есть ряд настроек, многие из которых важны и должны быть установлены.
Эти настройки указываются после пары ключ=значение и отделены друг от друга разделителем ; , вот так:
- path=/mypath
URL-префикс пути, куки будут доступны для страниц под этим путём. Должен быть абсолютным. По умолчанию используется текущий путь.
Если куки установлено с path=/admin , то оно будет доступно на страницах /admin и /admin/something , но не на страницах /home или /adminpage .
Как правило, указывают в качестве пути корень path=/ , чтобы наше куки было доступно на всех страницах сайта.
domain
- domain=site.com
Домен определяет, где доступен файл куки. Однако на практике существуют определённые ограничения. Мы не можем указать здесь какой угодно домен.
Нет никакого способа разрешить доступ к файлам куки из другого домена 2-го уровня, поэтому other.com никогда не получит куки, установленный по адресу site.com .
Это ограничение безопасности, позволяющее нам хранить конфиденциальные данные в файлах куки, которые должны быть доступны только на одном сайте.
По умолчанию куки доступны лишь тому домену, который его установил.
Пожалуйста, обратите внимание, что по умолчанию файл куки также не передаётся поддомену, например forum.site.com .
…Но это можно изменить. Если мы хотим разрешить поддоменам типа forum.site.com получать куки, установленные на site.com , это возможно.
Чтобы это произошло, при установке файла куки в site.com , мы должны явно установить параметр domain для корневого домена: domain=site.com . После этого все поддомены увидят такой файл cookie.
По историческим причинам установка domain=.site.com (с точкой перед site.com ) также работает и разрешает доступ к куки для поддоменов. Это старая запись, но можно использовать и её, если нужно, чтобы поддерживались очень старые браузеры.
Таким образом, опция domain позволяет нам разрешить доступ к куки для поддоменов.
expires, max-age
По умолчанию, если куки не имеют ни одного из этих параметров, то они удалятся при закрытии браузера. Такие куки называются сессионными («session cookies»).
Чтобы помочь куки «пережить» закрытие браузера, мы можем установить значение опций expires или max-age .
- expires=Tue, 19 Jan 2038 03:14:07 GMT
Дата истечения срока действия куки, когда браузер удалит его автоматически.
Дата должна быть точно в этом формате, во временной зоне GMT. Мы можем использовать date.toUTCString , чтобы получить правильную дату. Например, мы можем установить срок действия куки на 1 день.
Если мы установим в expires прошедшую дату, то куки будет удалено.
- max-age=3600
Альтернатива expires , определяет срок действия куки в секундах с текущего момента.
Если задан ноль или отрицательное значение, то куки будет удалено:
secure
- secure
Куки следует передавать только по HTTPS-протоколу.
По умолчанию куки, установленные сайтом http://site.com , также будут доступны на сайте https://site.com и наоборот.
То есть, куки, по умолчанию, опираются на доменное имя, они не обращают внимания на протоколы.
С этой настройкой, если куки будет установлено на сайте https://site.com , то оно не будет доступно на том же сайте с протоколом HTTP, как http://site.com . Таким образом, если в куки хранится конфиденциальная информация, которую не следует передавать по незашифрованному протоколу HTTP, то нужно установить этот флаг.
samesite
Это ещё одна настройка безопасности, применяется для защиты от так называемой XSRF-атаки (межсайтовая подделка запроса).
Чтобы понять, как настройка работает и где может быть полезной, посмотрим на XSRF-атаки.
Атака XSRF
Представьте, вы авторизовались на сайте bank.com . То есть: у вас есть куки для аутентификации с этого сайта. Ваш браузер отправляет его на сайт bank.com с каждым запросом, чтобы сервер этого сайта узнавал вас и выполнял все конфиденциальные финансовые операции.
Теперь, просматривая веб-страницу в другом окне, вы случайно переходите на сайт evil.com , который автоматически отправляет форму <form action="https://bank.com/pay"> на сайт bank.com с заполненными полями, которые инициируют транзакцию на счёт хакера.
Браузер посылает куки при каждом посещении bank.com , даже если форма была отправлена с evil.com . Таким образом, банк узнает вас и выполнит платёж.
Такая атака называется межсайтовая подделка запроса (или Cross-Site Request Forgery, XSRF).
Конечно же, в реальной жизни банки защищены от такой атаки. Во всех сгенерированных сайтом bank.com формах есть специальное поле, так называемый «токен защиты от xsrf», который вредоносная страница не может ни сгенерировать, ни каким-либо образом извлечь из удалённой страницы (она может отправить форму туда, но не может получить данные обратно). И сайт bank.com при получении формы проверяет его наличие.
Но такая защита требует усилий на её реализацию: нам нужно убедиться, что в каждой форме есть поле с токеном, также мы должны проверить все запросы.
Настройка samesite
Параметр куки samesite предоставляет ещё один способ защиты от таких атак, который (теоретически) не должен требовать «токенов защиты xsrf».
У него есть два возможных значения:
- samesite=strict (или, что то же самое, samesite без значения)
Куки с samesite=strict никогда не отправятся, если пользователь пришёл не с этого же сайта.
Другими словами, если пользователь переходит по ссылке из почты, отправляет форму с evil.com или выполняет любую другую операцию, происходящую с другого домена, то куки не отправляется.
Если куки имеют настройку samesite , то атака XSRF не имеет шансов на успех, потому что отправка с сайта evil.com происходит без куки. Таким образом, сайт bank.com не распознает пользователя и не произведёт платёж.
Защита довольно надёжная. Куки с настройкой samesite будет отправлено только в том случае, если операции происходят с сайта bank.com , например отправка формы сделана со страницы на bank.com .
Хотя есть небольшие неудобства.
Когда пользователь перейдёт по ссылке на bank.com , например из своих заметок, он будет удивлён, что сайт bank.com не узнал его. Действительно, куки с samesite=strict в этом случае не отправляется.
Мы могли бы обойти это ограничение, используя два куки: одно куки для «общего узнавания», только для того, чтобы поздороваться: «Привет, Джон», и другое куки для операций изменения данных с samesite=strict . Тогда пользователь, пришедший на сайт, увидит приветствие, но платежи нужно инициировать с сайта банка, чтобы отправилось второе куки.
- samesite=lax
Это более мягкий вариант, который также защищает от XSRF и при этом не портит впечатление от использования сайта.
Режим Lax так же, как и strict , запрещает браузеру отправлять куки, когда запрос происходит не с сайта, но добавляет одно исключение.
Куки с samesite=lax отправляется, если два этих условия верны:
Используются безопасные HTTP-методы (например, GET, но не POST).
Полный список безопасных HTTP-методов можно посмотреть в спецификации RFC7231. По сути, безопасными считаются методы, которые обычно используются для чтения, но не для записи данных. Они не должны выполнять никаких операций на изменение данных. Переход по ссылке является всегда GET-методом, то есть безопасным.
Операция осуществляет навигацию верхнего уровня (изменяет URL в адресной строке браузера).
Обычно это так, но если навигация выполняется в <iframe> , то это не верхний уровень. Кроме того, JavaScript-методы для сетевых запросов не выполняют никакой навигации, поэтому они не подходят.
Таким образом, режим samesite=lax , позволяет самой распространённой операции «переход по ссылке» передавать куки. Например, открытие сайта из заметок удовлетворяет этим условиям.
Но что-то более сложное, например, сетевой запрос с другого сайта или отправка формы, теряет куки.
Если это вам подходит, то добавление samesite=lax , скорее всего, не испортит впечатление пользователей от работы с сайтом и добавит защиту.
В целом, samesite отличная настройка.
Но у неё есть важный недостаток:
- samesite игнорируется (не поддерживается) старыми браузерами, выпущенными до 2017 года и ранее.
Так что, если мы будем полагаться исключительно на samesite , то старые браузеры будут уязвимы.
Но мы, безусловно, можем использовать samesite вместе с другими методами защиты, такими как XSRF-токены, чтобы добавить дополнительный слой защиты, а затем, в будущем, когда старые браузеры полностью исчезнут, мы, вероятно, сможем полностью удалить XSRF-токены.
httpOnly
Эта настройка не имеет ничего общего с JavaScript, но мы должны упомянуть её для полноты изложения.
Веб-сервер использует заголовок Set-Cookie для установки куки. И он может установить настройку httpOnly .
Эта настройка запрещает любой доступ к куки из JavaScript. Мы не можем видеть такое куки или манипулировать им с помощью document.cookie .
Эта настройка используется в качестве меры предосторожности от определённых атак, когда хакер внедряет свой собственный JavaScript-код в страницу и ждёт, когда пользователь посетит её. Это вообще не должно быть возможным, хакер не должен быть в состоянии внедрить свой код на ваш сайт, но могут быть ошибки, которые позволят хакеру сделать это.
Обычно, если такое происходит, и пользователь заходит на страницу с JavaScript-кодом хакера, то этот код выполняется и получает доступ к document.cookie , и тем самым к куки пользователя, которые содержат аутентификационную информацию. Это плохо.
Но если куки имеет настройку httpOnly , то document.cookie не видит его, поэтому такое куки защищено.
Приложение: Функции для работы с куки
Вот небольшой набор функций для работы с куки, более удобных, чем ручная модификация document.cookie .
Для этого существует множество библиотек, так что они, скорее, в демонстрационных целях. Но при этом полностью рабочие.
getCookie(name)
Самый короткий способ получить доступ к куки – это использовать регулярные выражения.
Функция getCookie(name) возвращает куки с указанным name :
Здесь new RegExp генерируется динамически, чтобы находить ; name=<value> .
Обратите внимание, значение куки кодируется, поэтому getCookie использует встроенную функцию decodeURIComponent для декодирования.
setCookie(name, value, options)
Устанавливает куки с именем name и значением value , с настройкой path=/ по умолчанию (можно изменить, чтобы добавить другие значения по умолчанию):
deleteCookie(name)
Чтобы удалить куки, мы можем установить отрицательную дату истечения срока действия:
Обратите внимание: когда мы обновляем или удаляем куки, нам следует использовать только такие же настройки пути и домена, как при установке куки.
Приложение: Сторонние куки
Куки называются сторонними, если они размещены с домена, отличающегося от страницы, которую посещает пользователь.
Страница site.com загружает баннер с другого сайта: <img src="https://ads.com/banner.png"> .
Вместе с баннером удалённый сервер ads.com может установить заголовок Set-Cookie с куки, например, id=1234 . Такие куки создаются с домена ads.com и будут видны только на сайте ads.com :
В следующий раз при доступе к ads.com удалённый сервер получит куки id и распознает пользователя:
Что ещё более важно, когда пользователь переходит с site.com на другой сайт other.com , на котором тоже есть баннер, то ads.com получит куки, так как они принадлежат ads.com , таким образом ads.com распознает пользователя и может отслеживать его перемещения между сайтами:
Сторонние куки в силу своей специфики обычно используются для целей отслеживания посещаемых пользователем страниц и показа рекламы. Они привязаны к исходному домену, поэтому ads.com может отслеживать одного и того же пользователя на разных сайтах, если оттуда идёт обращение к нему.
Естественно, некоторым пользователям не нравится, когда их отслеживают, поэтому браузеры позволяют отключать такие куки.
Кроме того, некоторые современные браузеры используют специальные политики для таких куки:
- Safari вообще не разрешает сторонние куки.
- У Firefox есть «чёрный список» сторонних доменов, чьи сторонние куки он блокирует.
Если мы загружаем скрипт со стороннего домена, например <script src="https://google-analytics.com/analytics.js"> , и этот скрипт использует document.cookie , чтобы установить куки, то такое куки не является сторонним.
Если скрипт устанавливает куки, то нет разницы откуда был загружен скрипт – куки принадлежит домену текущей веб-страницы.
Приложение: GDPR
Эта тема вообще не связана с JavaScript, но следует её иметь в виду при установке куки.
В Европе существует законодательство под названием GDPR, которое устанавливает для сайтов ряд правил, обеспечивающих конфиденциальность пользователей. И одним из таких правил является требование явного разрешения от пользователя на использование отслеживающих куки.
Обратите внимание, это относится только к куки, используемым для отслеживания/идентификации/авторизации.
То есть, если мы установим куки, которые просто сохраняют некоторую информацию, но не отслеживают и не идентифицируют пользователя, то мы свободны от этого правила.
Но если мы собираемся установить куки с информацией об аутентификации или с идентификатором отслеживания, то пользователь должен явно разрешить это.
Есть два основных варианта как сайты следуют GDPR. Вы наверняка уже видели их в сети:
Если сайт хочет установить куки для отслеживания только для авторизованных пользователей.
То в регистрационной форме должен быть установлен флажок «принять политику конфиденциальности» (которая определяет, как используются куки), пользователь должен установить его, и только тогда сайт сможет использовать авторизационные куки.
Если сайт хочет установить куки для отслеживания всем пользователям.
Чтобы сделать это законно, сайт показывает модальное окно для пользователей, которые зашли в первый раз, и требует от них согласие на использование куки. Затем сайт может установить такие куки и показать пользователю содержимое страницы. Хотя это создаёт неудобства для новых посетителей – никому не нравится наблюдать модальные окна вместо контента. Но GDPR в данной ситуации требует явного согласия пользователя.
GDPR касается не только куки, но и других вопросов, связанных с конфиденциальностью, которые выходят за рамки материала этой главы.
JavaScript Cookies
Cookies are data, stored in small text files, on your computer.
When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.
Cookies were invented to solve the problem "how to remember information about the user":
- When a user visits a web page, his/her name can be stored in a cookie.
- Next time the user visits the page, the cookie "remembers" his/her name.
Cookies are saved in name-value pairs like:
When a browser requests a web page from a server, cookies belonging to the page are added to the request. This way the server gets the necessary data to "remember" information about users.
None of the examples below will work if your browser has local cookies support turned off.
Create a Cookie with JavaScript
JavaScript can create, read, and delete cookies with the document.cookie property.
With JavaScript, a cookie can be created like this:
You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.
Read a Cookie with JavaScript
With JavaScript, cookies can be read like this:
document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;
Change a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you create it:
The old cookie is overwritten.
Delete a Cookie with JavaScript
Deleting a cookie is very simple.
You don’t have to specify a cookie value when you delete a cookie.
Just set the expires parameter to a past date:
You should define the cookie path to ensure that you delete the right cookie.
Some browsers will not let you delete a cookie if you don’t specify the path.
The Cookie String
The document.cookie property looks like a normal text string. But it is not.
Even if you write a whole cookie string to document.cookie, when you read it out again, you can only see the name-value pair of it.
If you set a new cookie, older cookies are not overwritten. The new cookie is added to document.cookie, so if you read document.cookie again you will get something like:
cookie1 = value; cookie2 = value;
Display All Cookies Create Cookie 1 Create Cookie 2 Delete Cookie 1 Delete Cookie 2
If you want to find the value of one specified cookie, you must write a JavaScript function that searches for the cookie value in the cookie string.
JavaScript Cookie Example
In the example to follow, we will create a cookie that stores the name of a visitor.
The first time a visitor arrives to the web page, he/she will be asked to fill in his/her name. The name is then stored in a cookie.
The next time the visitor arrives at the same page, he/she will get a welcome message.
For the example we will create 3 JavaScript functions:
- A function to set a cookie value
- A function to get a cookie value
- A function to check a cookie value
A Function to Set a Cookie
First, we create a function that stores the name of the visitor in a cookie variable:
Example
Example explained:
The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).
The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.
A Function to Get a Cookie
Then, we create a function that returns the value of a specified cookie:
Example
Function explained:
Take the cookiename as parameter (cname).
Create a variable (name) with the text to search for (cname + "=").
Decode the cookie string, to handle cookies with special characters, e.g. ‘$’
Split document.cookie on semicolons into an array called ca (ca = decodedCookie.split(‘;’)).
Loop through the ca array (i = 0; i < ca.length; i++), and read out each value c = ca[i]).
If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length, c.length).
If the cookie is not found, return "".
A Function to Check a Cookie
Last, we create the function that checks if a cookie is set.
If the cookie is set it will display a greeting.
If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:
Example
All Together Now
Example
function setCookie(cname, cvalue, exdays) <
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
>
function getCookie(cname) <
let name = cname + "=";
let ca = document.cookie.split(‘;’);
for(let i = 0; i < ca.length; i++) <
let c = ca[i];
while (c.charAt(0) == ‘ ‘) <
c = c.substring(1);
>
if (c.indexOf(name) == 0) <
return c.substring(name.length, c.length);
>
>
return "";
>
function checkCookie() <
let user = getCookie("username");
if (user != "") <
alert("Welcome again " + user);
> else <
user = prompt("Please enter your name:", "");
if (user != "" && user != null) <
setCookie("username", user, 365);
>
>
>
Cookies, document.cookie
Cookies are small strings of data that are stored directly in the browser. They are a part of the HTTP protocol, defined by the RFC 6265 specification.
Cookies are usually set by a web-server using the response Set-Cookie HTTP-header. Then, the browser automatically adds them to (almost) every request to the same domain using the Cookie HTTP-header.
One of the most widespread use cases is authentication:
- Upon sign in, the server uses the Set-Cookie HTTP-header in the response to set a cookie with a unique “session identifier”.
- Next time when the request is sent to the same domain, the browser sends the cookie over the net using the Cookie HTTP-header.
- So the server knows who made the request.
We can also access cookies from the browser, using document.cookie property.
There are many tricky things about cookies and their options. In this chapter we’ll cover them in detail.
Reading from document.cookie
Does your browser store any cookies from this site? Let’s see:
The value of document.cookie consists of name=value pairs, delimited by ; . Each one is a separate cookie.
To find a particular cookie, we can split document.cookie by ; , and then find the right name. We can use either a regular expression or array functions to do that.
We leave it as an exercise for the reader. Also, at the end of the chapter you’ll find helper functions to manipulate cookies.
Writing to document.cookie
We can write to document.cookie . But it’s not a data property, it’s an accessor (getter/setter). An assignment to it is treated specially.
A write operation to document.cookie updates only cookies mentioned in it, but doesn’t touch other cookies.
For instance, this call sets a cookie with the name user and value John :
If you run it, then probably you’ll see multiple cookies. That’s because the document.cookie= operation does not overwrite all cookies. It only sets the mentioned cookie user .
Technically, name and value can have any characters. To keep the valid formatting, they should be escaped using a built-in encodeURIComponent function:
There are few limitations:
- The name=value pair, after encodeURIComponent , should not exceed 4KB. So we can’t store anything huge in a cookie.
- The total number of cookies per domain is limited to around 20+, the exact limit depends on the browser.
Cookies have several options, many of them are important and should be set.
The options are listed after key=value , delimited by ; , like this:
- path=/mypath
The url path prefix must be absolute. It makes the cookie accessible for pages under that path. By default, it’s the current path.
If a cookie is set with path=/admin , it’s visible at pages /admin and /admin/something , but not at /home or /adminpage .
Usually, we should set path to the root: path=/ to make the cookie accessible from all website pages.
domain
- domain=site.com
A domain defines where the cookie is accessible. In practice though, there are limitations. We can’t set any domain.
There’s no way to let a cookie be accessible from another 2nd-level domain, so other.com will never receive a cookie set at site.com .
It’s a safety restriction, to allow us to store sensitive data in cookies that should be available only on one site.
By default, a cookie is accessible only at the domain that set it.
Please note, by default a cookie is also not shared to a subdomain as well, such as forum.site.com .
…But this can be changed. If we’d like to allow subdomains like forum.site.com to get a cookie set at site.com , that’s possible.
For that to happen, when setting a cookie at site.com , we should explicitly set the domain option to the root domain: domain=site.com . Then all subdomains will see such cookie.
For historical reasons, domain=.site.com (with a dot before site.com ) also works the same way, allowing access to the cookie from subdomains. That’s an old notation and should be used if we need to support very old browsers.
To summarize, the domain option allows to make a cookie accessible at subdomains.
expires, max-age
By default, if a cookie doesn’t have one of these options, it disappears when the browser is closed. Such cookies are called “session cookies”
To let cookies survive a browser close, we can set either the expires or max-age option.
- expires=Tue, 19 Jan 2038 03:14:07 GMT
The cookie expiration date defines the time, when the browser will automatically delete it.
The date must be exactly in this format, in the GMT timezone. We can use date.toUTCString to get it. For instance, we can set the cookie to expire in 1 day:
If we set expires to a date in the past, the cookie is deleted.
- max-age=3600
It’s an alternative to expires and specifies the cookie’s expiration in seconds from the current moment.
If set to zero or a negative value, the cookie is deleted:
secure
- secure
The cookie should be transferred only over HTTPS.
By default, if we set a cookie at http://site.com , then it also appears at https://site.com and vice versa.
That is, cookies are domain-based, they do not distinguish between the protocols.
With this option, if a cookie is set by https://site.com , then it doesn’t appear when the same site is accessed by HTTP, as http://site.com . So if a cookie has sensitive content that should never be sent over unencrypted HTTP, the secure flag is the right thing.
samesite
That’s another security attribute samesite . It’s designed to protect from so-called XSRF (cross-site request forgery) attacks.
To understand how it works and when it’s useful, let’s take a look at XSRF attacks.
XSRF attack
Imagine, you are logged into the site bank.com . That is: you have an authentication cookie from that site. Your browser sends it to bank.com with every request, so that it recognizes you and performs all sensitive financial operations.
Now, while browsing the web in another window, you accidentally come to another site evil.com . That site has JavaScript code that submits a form <form action="https://bank.com/pay"> to bank.com with fields that initiate a transaction to the hacker’s account.
The browser sends cookies every time you visit the site bank.com , even if the form was submitted from evil.com . So the bank recognizes you and actually performs the payment.
That’s a so-called “Cross-Site Request Forgery” (in short, XSRF) attack.
Real banks are protected from it of course. All forms generated by bank.com have a special field, a so-called “XSRF protection token”, that an evil page can’t generate or extract from a remote page. It can submit a form there, but can’t get the data back. The site bank.com checks for such token in every form it receives.
Such a protection takes time to implement though. We need to ensure that every form has the required token field, and we must also check all requests.
Enter cookie samesite option
The cookie samesite option provides another way to protect from such attacks, that (in theory) should not require “xsrf protection tokens”.
It has two possible values:
- samesite=strict (same as samesite without value)
A cookie with samesite=strict is never sent if the user comes from outside the same site.
In other words, whether a user follows a link from their mail or submits a form from evil.com , or does any operation that originates from another domain, the cookie is not sent.
If authentication cookies have the samesite option, then a XSRF attack has no chances to succeed, because a submission from evil.com comes without cookies. So bank.com will not recognize the user and will not proceed with the payment.
The protection is quite reliable. Only operations that come from bank.com will send the samesite cookie, e.g. a form submission from another page at bank.com .
Although, there’s a small inconvenience.
When a user follows a legitimate link to bank.com , like from their own notes, they’ll be surprised that bank.com does not recognize them. Indeed, samesite=strict cookies are not sent in that case.
We could work around that by using two cookies: one for “general recognition”, only for the purposes of saying: “Hello, John”, and the other one for data-changing operations with samesite=strict . Then, a person coming from outside of the site will see a welcome, but payments must be initiated from the bank’s website, for the second cookie to be sent.
- samesite=lax
A more relaxed approach that also protects from XSRF and doesn’t break the user experience.
Lax mode, just like strict , forbids the browser to send cookies when coming from outside the site, but adds an exception.
A samesite=lax cookie is sent if both of these conditions are true:
The HTTP method is “safe” (e.g. GET, but not POST).
The full list of safe HTTP methods is in the RFC7231 specification. Basically, these are the methods that should be used for reading, but not writing the data. They must not perform any data-changing operations. Following a link is always GET, the safe method.
The operation performs a top-level navigation (changes URL in the browser address bar).
That’s usually true, but if the navigation is performed in an <iframe> , then it’s not top-level. Also, JavaScript methods for network requests do not perform any navigation, hence they don’t fit.
So, what samesite=lax does, is to basically allow the most common “go to URL” operation to have cookies. E.g. opening a website link from notes that satisfy these conditions.
But anything more complicated, like a network request from another site or a form submission, loses cookies.
If that’s fine for you, then adding samesite=lax will probably not break the user experience and add protection.
Overall, samesite is a great option.
There’s a drawback:
- samesite is ignored (not supported) by very old browsers, year 2017 or so.
So if we solely rely on samesite to provide protection, then old browsers will be vulnerable.
But we surely can use samesite together with other protection measures, like xsrf tokens, to add an additional layer of defence and then, in the future, when old browsers die out, we’ll probably be able to drop xsrf tokens.
httpOnly
This option has nothing to do with JavaScript, but we have to mention it for completeness.
The web-server uses the Set-Cookie header to set a cookie. Also, it may set the httpOnly option.
This option forbids any JavaScript access to the cookie. We can’t see such a cookie or manipulate it using document.cookie .
That’s used as a precaution measure, to protect from certain attacks when a hacker injects his own JavaScript code into a page and waits for a user to visit that page. That shouldn’t be possible at all, hackers should not be able to inject their code into our site, but there may be bugs that let them do it.
Normally, if such a thing happens, and a user visits a web-page with hacker’s JavaScript code, then that code executes and gains access to document.cookie with user cookies containing authentication information. That’s bad.
But if a cookie is httpOnly , then document.cookie doesn’t see it, so it is protected.
Appendix: Cookie functions
Here’s a small set of functions to work with cookies, more convenient than a manual modification of document.cookie .
There exist many cookie libraries for that, so these are for demo purposes. Fully working though.
getCookie(name)
The shortest way to access a cookie is to use a regular expression.
The function getCookie(name) returns the cookie with the given name :
Here new RegExp is generated dynamically, to match ; name=<value> .
Please note that a cookie value is encoded, so getCookie uses a built-in decodeURIComponent function to decode it.
setCookie(name, value, options)
Sets the cookie’s name to the given value with path=/ by default (can be modified to add other defaults):
Document: cookie property
The Document property cookie lets you read and write cookies associated with the document. It serves as a getter and setter for the actual values of the cookies.
Syntax
Read all cookies accessible from this location
In the code above allCookies is a string containing a semicolon-separated list of all cookies (i.e. key=value pairs). Note that each key and value may be surrounded by whitespace (space and tab characters): in fact, RFC 6265 mandates a single space after each semicolon, but some user agents may not abide by this.
Write a new cookie
In the code above, newCookie is a string of form key=value , specifying the cookie to set/update. Note that you can only set/update a single cookie at a time using this method. Consider also that:
-
Any of the following cookie attribute values can optionally follow the key-value pair, each preceded by a semicolon separator:
- The lax value will send the cookie for all same-site requests and top-level navigation GET requests. This is sufficient for user tracking, but it will prevent many Cross-Site Request Forgery (CSRF) attacks. This is the default value in modern browsers.
- The strict value will prevent the cookie from being sent by the browser to the target site in all cross-site browsing contexts, even when following a regular link.
- The none value explicitly states no restrictions will be applied. The cookie will be sent in all requests—both cross-site and same-site.
- __Secure- Signals to the browser that it should only include the cookie in requests transmitted over a secure channel.
- __Host- Signals to the browser that in addition to the restriction to only use the cookie from a secure origin, the scope of the cookie is limited to a path attribute passed down by the server. If the server omits the path attribute the «directory» of the request URI is used. It also signals that the domain attribute must not be present, which prevents the cookie from being sent to other domains. For Chrome the path attribute must always be the origin.
-
;domain=domain (e.g., ‘ example.com ‘ or ‘ subdomain.example.com ‘): The host to which the cookie will be sent. If not specified, this defaults to the host portion of the current document location. Contrary to earlier specifications, leading dots in domain names are ignored, but browsers may decline to set the cookie containing such dots. If a domain is specified, subdomains are always included.
Note: The domain must match the domain of the JavaScript origin. Setting cookies to foreign domains will be silently ignored.
Warning: When user privacy is a concern, it’s important that any web app implementation invalidate cookie data after a certain timeout instead of relying on the browser to do it. Many browsers let users specify that cookies should never expire, which is not necessarily safe.
Note: The dash is considered part of the prefix.
Note: These flags are only settable with the secure attribute.