To secure your web app, you must prevent XSS by validating and sanitizing all user input to stop malicious scripts from running in a user’s browser. You prevent CSRF by using anti-CSRF tokens to ensure that state-changing requests are legitimate and not forged by an attacker.
XSS (Cross-Site Scripting): The Impersonation Attack 🎭
An XSS attack tricks a website into running malicious JavaScript in a victim’s browser. The script then runs with the full trust and permissions of the website, allowing it to steal the user’s session cookies, passwords, or manipulate the page content.
Analogy: The Fake Poster An XSS attack is like a scammer tricking a coffee shop owner into putting a malicious poster on their official notice board. When customers come in, they read the poster and, thinking it’s from the trusted coffee shop, follow its bad instructions (e.g., “scan this QR code for a free coffee”). The attacker’s scam works because it’s presented in a trusted environment.
How to Prevent XSS: The golden rule is to never trust user input.
- Output Encoding: Before displaying any user-provided data in your HTML, encode it so the browser treats it as plain text, not executable code. For example,
<script>becomes<script>. - Content Security Policy (CSP): This is a powerful defense-in-depth measure. A CSP is an HTTP header that tells the browser which domains are allowed to execute scripts on your page, effectively blocking unauthorized scripts from running.
CSRF (Cross-Site Request Forgery): The Forged Request Attack forgery ✉️
A CSRF attack tricks a logged-in user into unknowingly submitting a malicious request to a website. The website trusts the request because it comes from the user’s authenticated browser.
Analogy: The Pre-Signed Check A CSRF attack is like a scammer handing you a pre-filled-out check to an offshore account. You are already “logged in” to your bank, and you unknowingly sign it (by clicking a disguised link on another site). The bank processes the check because it has your legitimate signature. The bank trusts the who (you), but doesn’t verify the intent.
How to Prevent CSRF: The goal is to verify that the user intended to make the request.
- Anti-CSRF Tokens: This is the most common defense. The server generates a unique, secret, and unpredictable token for each user session and embeds it in a hidden field in a form. When the user submits the form, the token is sent back. The server validates that the received token matches the one it issued, proving the request came from the original site.
- SameSite Cookies: This is a browser-level defense where you can set a cookie attribute that prevents it from being sent with cross-site requests, effectively stopping most CSRF attacks.