Reading a token by hand
Split the token at the two dots. The first part almost always starts with eyJ, which is what {" looks like in Base64. Decoded, the header below says the token is signed with HMAC-SHA256:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
→ {"alg":"HS256","typ":"JWT"}
JWTs use Base64URL, which swaps + and / for - and _ and drops the = padding at the end. That is why pasting a JWT part into an ordinary Base64 decoder sometimes fails or gives garbage at the end.
Decoding a JWT in JavaScript or Python
// JavaScript (browser or Node 16+)
const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')
const claims = JSON.parse(atob(part))
# Python: pip install PyJWT
import jwt
claims = jwt.decode(token, options={"verify_signature": False})
The JavaScript version mangles accented letters and other non-ASCII text, so use a library such as jwt-decode when names can contain them. Keep unverified decoding for display and debugging. On a server, always verify with the key and a fixed list of allowed algorithms, for example jwt.decode(token, key, algorithms=["RS256"]).
Why a good-looking token is rejected
- Expired: exp is in the past. Many APIs issue access tokens that last only 5 to 60 minutes.
- Clock skew: the server’s clock is a little behind or ahead, so a fresh token looks not yet valid (nbf) or already expired. Most libraries accept a leeway setting of 30 to 60 seconds.
- Wrong audience or issuer: aud or iss does not match what the API expects, which often happens when a token from the staging login is used against production.
- Rotated keys: the kid in the header points to a key the server no longer has. Reload the JWKS from the issuer.
- Copy damage: the word Bearer, a space or a line break was pasted into the token itself.
Storing tokens safely in a web app
A token in localStorage can be read by any script on the page, so a single cross-site scripting bug leaks it. An HttpOnly, Secure, SameSite cookie keeps it away from scripts, but then the site needs protection against cross-site request forgery. Whichever you choose, keep access tokens short-lived and renew them with a refresh token. And never put secrets or personal details in the payload: anyone who holds the token can read every claim, as this page shows.