Cross-site scripting attack exploits web security vulnerabilities by allowing an attacker to inject malicious JavaScript code into otherwise benign and safe websites.
Note: To know more about XSS, please refer to this answer.
If successful, XSS can lead to the attacker accessing user session information, such as cookies and other private information. A cookie can be read by JavaScript in the browser through the document.cookie
property.
Cookies are a mechanism to track and personalize a user's session or activity online. They facilitate the digital experience by remembering information such as log-in credentials for accounts, shopping cart contents, and browsing history.
On their own, cookies are not harmful. However, if these cookies are leaked, an attacker can access the victim's private accounts, including social media and email. Moreover, these leaked cookies can be used to track the victim's internet activity, which breaches privacy.
HttpOnly
attributeTo prevent cookies from being accessed and exploited, we can use HttpOnly
, an attribute of the Set-Cookie
header that allows cookies to be set by the server. It ensures that the cookie is accessed and read only by the HTTP response of the server and not through JavaScript's document.cookie
property. Therefore, malicious JavaScript will not be able to exploit user cookies and subsequently track their digital footprint.
A sample command of the Set-Cookie
header with the HttpOnly
attribute is shown below:
Set-Cookie: id=abc; Secure; HttpOnly
The following parameters are included in the syntax above:
id
: This attribute is a unique identifier for the cookie.
Secure
: This ensures the cookie is only sent if the request is over a secure channel such as HTTPS. It helps prevent man-in-the-middle attacks.
HttpOnly
: This helps mitigate XSS attacks by preventing cookie access by JavaScript.
Free Resources