Bearer Token Authentication
You'll learn how sending tokens in the Authorization header protects against CSRF but requires careful XSS prevention.
What is Bearer Token Authentication?
Bearer token authentication means sending your access token in the HTTP Authorization header using this format:
Authorization: Bearer YOUR_TOKEN_HERE
This is the most common approach for stateless authentication with JWTs or similar tokens. The word "bearer" literally means "whoever holds this token" — the server trusts anyone who presents a valid token without additional proof.
Why This Prevents CSRF
Unlike cookies (which browsers send automatically), the Authorization header must be explicitly set by JavaScript code:
fetch('/api/user', {
headers: {
'Authorization': `Bearer ${token}`
}
});
CSRF attacks fail because a malicious site cannot force your browser to add custom headers to cross-origin requests. The attacker's page can trigger a fetch request to your API, but it cannot read your stored token (from localStorage or a variable) due to Same-Origin Policy, nor can it set the Authorization header on your behalf.
The XSS Trade-Off
The security benefit comes with a critical requirement: you must store the token somewhere JavaScript can access it (localStorage, sessionStorage, or memory). This makes your tokens vulnerable to XSS attacks — if an attacker injects malicious JavaScript into your page, they can steal the token.
Think of it like keeping your house key in your pocket vs. your car's automatic door opener. CSRF is like someone tricking your car into unlocking from a distance — bearer tokens are like pocket keys that can't be remotely activated, but they can be pickpocketed if someone gets close enough.
Key Takeaway: Bearer tokens in Authorization headers naturally prevent CSRF because they require explicit JavaScript action, but this makes rigorous XSS prevention (CSP, input sanitization, output encoding) absolutely essential.