javascriptcookiesxsscookie-httponly

How does httpOnly prevent from malicious package to steal the content in it?


If for example, an installed third party package issues an HTTP request to their servers, and by default, any HTTP request leaves with the cookies content in the request headers, doesn't it make the content to be exposed to the server who receives the request? I don't get how httpOnly prevents from the access token to be revealed...


Solution

  • 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.