How does token-based authentication with JWT work? What are the three parts of a JWT, where is it sent in a request, and what are its main risks?
Show the explanation
Model answer. After a successful login the server issues a JSON Web Token. The client sends it with every request, and the server verifies the signature instead of looking up a session, so it is stateless.
A JWT is three base64url parts joined by dots: header.payload.signature.
- Header: the algorithm, e.g.
{"alg":"HS256","typ":"JWT"}. - Payload: claims such as the user id (
sub), role, and expiry (exp). It is encoded, not encrypted: anyone can read it, so never put secrets in it. - Signature: made from the header and payload with a secret or private key, so any tampering is detected.
Where it travels: usually the Authorization: Bearer <token> header; or an HttpOnly, Secure, SameSite cookie, which JavaScript cannot read (safer against XSS, but needs CSRF protection).
import jwt from 'jsonwebtoken';
const token = jwt.sign({ sub: user.id, role: 'student' }, process.env.JWT_SECRET, { expiresIn: '15m' });
const claims = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }); // throws if invalidRisks and mitigations:
- Cannot be revoked before expiry: keep access tokens short-lived and use refresh tokens that can be revoked.
- Stolen from localStorage via XSS: prefer HttpOnly cookies.
- Algorithm confusion: always pin the accepted algorithms when verifying.
Original UniCircle question. Last reviewed 22 Oct 2026.
