JSON Web Tokens, one hears all about them all the time. But what exactly are they? I’ve used them a thousand times myself but I never really checked out exactly what they are. So this post fills that gap for me, and hopefully it’s useful to a few of you readers out there too.
What is a JSON Web Token?
What are JWTs good for? When should you use a JWT?
The most common, and what I’ve found the most recommended use of JWTs, is for API authentication or server-to-server authorization.
Paraphrased and summarized using the Wikipedia example here.
The header identifies which algorithm generated the signature, such as HMAC-SHA256, as indicated in the example below.
Then the contenxt, or payload, contains the claims. There are seven Registered Claim Names (RCN) as standard fields commonly included in tokens. Custom claims can also be included, the following is the
At Time claim, designated
iat and custom claim of
loggedInAs. The others include:
exp (expiration time),
nbf (not before time),
iat (issued at time), and
jti (JWT ID). For these and many other claims the IANA has a resource here.
The signature securely validates the token. It’s calculated through encoding the header and payload using Base64url encoding per RFC 4648 and concatenated with a period as the seperator. This string is run through a cryptographic algorithm specified in the header (i.e. HMAC SHA 256). A function signature would look something like this.
base64urlEncoding(header) + '.' +
All concatenated together the token would then look like this.
Do and Do Nots
- Do not use JWTs as session tokens. At least in general, they have a wider range of features and a wider scope. Session tokens are a different beast and using JWTs can increase potential mistakes. Some other issues with this is a JWT doesn’t simply can’t be removed at the end of a session, as it is self-contained without a central authority, and another is that they’re relatively large for such a purpose.
- Do use JWTs for API Authentication. This is the most common use for JWTs today, as it fits the use case and in many ways was designed specifically for it.
- Do use a library or some other known way to generate JWT tokens. Don’t just randomly generate a string that looks like a JWT. I’ve seen people just generate a big ole’ wad of text that looks like a JWT before but then it is literally just a big wad of text, you can’t fake a JWT, and in turn when it’s verified or processed by a library for authentication purposes you’ll end up with errors and other issues.