How does httpOnly prevent from malicious package to steal the content in it?
Solution 1:
HTTP requests carry with it only cookies that are applicable to the domain being requested, not all of the browser's cookies. If you have a browser with cookies for bank.com
, shop.com
, and evil-site.com
, a request to evil-site.com
would only send evil-site.com
cookies with the request. Not so useful.
Now say a malicious script has infected bank.com
and has placed itself on a page in that domain. Now that script is running in the context of bank.com
and the currently viewing user. It can now read bank.com
's non-HttpOnly cookies using document.cookie
and send them to evil-site.com
with a simple script. This means that if you logged in to bank.com
and viewed that infected page, your login cookies can now be stolen.
Marking a cookie as HttpOnly
tells the browser not to expose the cookie to JavaScript, i.e. any script, legit or not, cannot read the cookie's value from document.cookie
. So if bank.com
made their login cookie HttpOnly
, this cookie would not be readable by any script on the page. However, the cookie is still passed back and forth between browser and bank.com
in requests and responses while the cookies are present and valid.
HttpOnly
is just one of the many measures to prevent cookie theft and should be complemented by other security features. Secure
makes sure the cookie is only ever sent through HTTPS connections. SameSite
defines when the cookie is allowed to cross sites. HTTPS connections prevent reading the request over the network.
Solution 2:
The httpOnly
attribute purpose is to hide the cookie from the JavaScript context.
To observe it, you can type document.cookie
in the console of any web page, and you'll notice that the result contains all of the cookies that are not httpOnly
and from the current domain. You can verify it with the Application tab of the DevTools.
That means if an attacker somehow manages to execute malicious code on a user's web page (e.g. by exploiting a script injection vulnerability), he may be able to send requests on behalf of that user but he should not be able to retrieve the cookie's value.