A JSON Web Token (JWT) is a compact, URL‑safe string that contains a set of claims about an entity and is cryptographically signed so the receiver can verify its integrity. In an interview you can start with a one‑sentence definition:
"A JWT is a self‑contained, signed token that carries user information and can be verified without a server‑side lookup."
How JWTs Work
Structure
A JWT has three Base64URL‑encoded parts separated by dots:
- Header – declares the signing algorithm (e.g.,
HS256orRS256). - Payload – the claims set (e.g.,
sub,iat,exp). - Signature – HMAC or RSA signature over
header.payload.
The resulting string looks like eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0.... Because the signature is verified with a shared secret or public key, the token can be trusted by any service that knows the key.
Typical Flow
- Login – client sends credentials to an auth server.
- Token Issuance – server creates a JWT, signs it, and returns it to the client.
- Client Storage – the token is stored (often in memory or a secure cookie).
- Request – client includes the token in the
Authorization: Bearer <jwt>header. - Verification – each service validates the signature and checks claim validity (expiry, audience, etc.).
Trade‑offs to Discuss
| Aspect | Advantage | Drawback |
|---|---|---|
| Statelessness | No session store; easy horizontal scaling. | Revoking a token before expiry requires extra mechanisms. |
| Performance | Signature verification is cheap; no DB round‑trip. | Token size adds overhead to each request. |
| Flexibility | Custom claims let you embed roles, scopes, etc. | Over‑embedding can expose sensitive data if not encrypted. |
| Security | Strong algorithms (RS256) protect against tampering. | If the secret/key leaks, all tokens are compromised. |
Mention that JWTs are not encrypted by default; they are only signed. If confidentiality is needed, you either encrypt the payload (JWE) or use transport‑level TLS.
Concrete Example
Imagine a SaaS product where users can access a dashboard after logging in.
// Auth server (Node/Express)
const jwt = require('jsonwebtoken');
app.post('/login', (req, res) => {
const user = authenticate(req.body);
const payload = { sub: user.id, role: user.role };
const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
});
// API server (protected route)
app.get('/reports', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
try {
const claims = jwt.verify(token, process.env.JWT_SECRET);
if (claims.role !== 'admin') return res.sendStatus(403);
res.json(getReports());
} catch (e) {
res.sendStatus(401);
}
});
The token carries the user’s ID and role, allowing the API to authorize without a database lookup. The expiresIn claim forces periodic re‑authentication, mitigating the revocation issue.
Questions Interviewers Often Ask
- Why use a JWT instead of a server‑side session? – Emphasize stateless scaling and reduced DB load, while acknowledging revocation challenges.
- How do you handle token revocation? – Mention short lifetimes, refresh tokens, or a token blacklist stored in a fast cache.
- What are the security risks of storing JWTs in localStorage? – Explain XSS exposure and recommend HttpOnly, Secure cookies for high‑risk apps.
- Can a JWT be encrypted? – Yes, via JWE, but most implementations rely on TLS for confidentiality.
- What happens if the signing key rotates? – Discuss key‑id (
kid) in the header and maintaining a key set for verification.
60‑Second Spoken Answer
"A JWT is a compact, signed token that contains claims about a user. It has three parts—header, payload, and signature—joined by dots. When a user logs in, the auth server signs a token with a secret or private key and sends it back. The client then includes the token in the Authorization header for subsequent requests. Because the token is self‑contained, any service that knows the signing key can verify it without hitting a session store, which makes horizontal scaling easy. The trade‑off is that revoking a token before its expiry is tricky, so we usually keep lifetimes short and use refresh tokens or a blacklist. In practice, a JWT might carry a user ID and role, letting an API authorize a request in a single step. The main security concerns are keeping the signing key secret and storing the token safely to avoid XSS attacks."
Frequently asked questions
When should I choose JWT over a traditional session cookie?
Pick JWT when you need stateless authentication across multiple services or domains, or when you want to embed user claims directly in the token. Use sessions if you need immediate revocation or want to keep sensitive data off the client.
How can I invalidate a JWT before it expires?
Common approaches are short token lifetimes with refresh tokens, maintaining a blacklist in a fast store, or rotating signing keys and using the `kid` header to identify valid keys.
Is storing a JWT in localStorage safe?
LocalStorage is vulnerable to XSS attacks, so for high‑risk applications it's safer to store the token in an HttpOnly, Secure cookie. If you must use localStorage, ensure strict Content‑Security‑Policy and sanitization.
Can JWTs be used for non‑authentication purposes?
Yes, they can carry any claims, such as feature flags or temporary permissions, but remember they are only signed—not encrypted—so avoid putting confidential data inside.
#concept#JWTs#authentication#security#interview