๐๐ช๐ง ๐ง๐ผ๐ธ๐ฒ๐ป๐ ๐ฆ๐ฒ๐ฐ๐๐ฟ๐ถ๐๐ ๐๐๐ถ๐ฑ๐ฒ
JWTs are in most web apps. Many developers use them wrong. This creates security holes.
A JWT is JSON data encoded in Base64. It has a digital signature. It is not a secret vault. Anyone who sees the token reads the data. The signature proves no one changed the data.
Three parts make a JWT:
- Header: Tells the algorithm.
- Payload: Holds user data.
- Signature: Stops tampering.
Check any JWT at jwt.io.
How it works:
- You log in.
- The server sends a signed JWT.
- Store the token in an httpOnly cookie.
- Send the token in the header.
- The server verifies the signature.
- The server skips the database lookup.
JWTs are stateless. They stay valid until they expire. This makes revocation hard.
Solutions:
- Set expiry to 15 minutes.
- Use refresh tokens.
- Store revoked IDs in Redis.
Security Rules:
- Verify the signature first.
- Use short expiry times.
- Use httpOnly cookies to block XSS.
- No secrets in the payload.
- Use RS256 over HS256.
- Check all claims.
Which algorithm to use:
- HS256: For simple apps.
- RS256: For microservices.
- ES256: For speed.
Key Takeaways:
- Sign tokens. Do not encrypt them.
- Keep tokens short.
- Store in httpOnly cookies.
- Validate everything on the server.
Source: https://dev.to/moksh/jwt-tokens-security-guide-what-every-developer-must-know-4gh9