'How does HttpOnly cookie protect against XSS/Injection attack if they are passed automatically with every request?

From what I understand, HttpOnly cookies cannot be read by client js but they are passed by the browser with any subsequent requests.

If an attacker is able to inject js in to a web page and makes a request to the endpoint, it would still go through because all cookies are passed along, correct?

What's the point of HttpOnly cookies?



Solution 1:[1]

If the request to site A is made from a site B, it's a Cross-Site Request Forgery (CSRF): An attacker gets a user to send a request (e.g. by luring the user into visiting an infected webpage) to the endpoint that should be attacked - when the user was already logged in there and a session is stored, the browser will send all cookies with the request to the endpoint and the attacker is able to perform operations on behalf of the user. Indeed, HttpOnly cookies do not help to prevent CSRF. What helps is setting the SameSite=Strict attribute when creating a cookie - this tells the browser to not send cookies when the HTTP(S) request was initiated on a different site. However, if a script (which sends an HTTP(S) request to the target) is injected to a site, it is a same-site request and therefore SameSite=Strict doesn't prevent the cookie from being sent (and again, also HttpOnly cookies don't prevent this attack).

But after all, what's the point of HttpOnly cookies then? They can be used to prevent cookie stealing through JavaScript. If an attacker manages to inject a script into a webpage, he could read the document.cookie property and starts an attack based on the cookies he retrieves (e.g. session hijacking).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1