JSON Web Tokens (JWT) — the only explanation you will ever need

JSON Web Tokens are truly changing the world.

Introduction

Hello! My name is Ariel. Over the past years I have worked in various industries (FinTech, Sports, Entertainment, BioTech). I’ve love doing a bit of everything — front-end, back-end, ops and leadership.

Why do we need JSON Web Tokens (JWTs)?

I always believe that requirements come first. Understanding why we need JWTs rather than diving right into the explanation will surely help.

Your typical front-end to back-end usage

The most shallow example would be a front-end application communicating with an API via HTTP requests. Using a JWT, you will be able to authorize the user. You could then take it one step further and use JWTs to perform role checks (for example, when a certain API route should only be available to admin users).

In distributed systems

JWTs are extremely useful in distributed systems and microservices architecture, utilising the Private-Public Key signing method. This method will save you a huge amount of requests and improve the overall scalability of your application. We will talk about that later on in this article.

The three components of a JSON Web Token

Part 1: The JWT Standard

JSON Web Token is a standard. A typical token will consist of a header, a payload and a signature. Let’s talk about each one of those and how they are utilised.

Header

The header contains metadata information about the JSON Web Token.

  • Algorithm (alg): The algorithm used to sign the token. This is useful for the attempted reproduction of the signature (we will talk about that later).
  • Type (typ): The type of the token. In the case of a JWT, this will always have the JWT value.

Payload

That’s what you’ve been waiting for. The payload will contain the claims of the token. There are several “recommended” standard fields that are defined in the JWT standard. Let’s talk about the most used ones:

  • Issuer (iss): The entity to generate and issue the JSON Web Token (for example, your authentication service or OAuth provider).
  • Subject (sub): The entity identified by this token. For example, if the token is used to authorize a user, sub could be the user ID.
  • Audience (aud): Target audience for this JWT. For example, if the token is intended to be used by your beta testers user pool, you could specify that as an audience. It is advised to reject tokens with no audience.
  • Expiry (exp): Specifies the timestamp (Unix) after which the token should not be accepted. We will talk about short-lived JWTs later on.
  • Issued at (iat): Specifies the date at which the token has been issued.
{
"sub": "1dfee8d8-98a5-4314-b4ae-fb55c4b18845",
"email": "ariel@codingly.io",
"name": "Ariel Weinberger",
"role": "ADMIN",
"iat": 1598607423,
"exp": 1598607723
}

Signature

Although we would like to believe that the magic of JWTs happens in the payload, it actually happens in the signature. This is probably the most commonly misunderstood part about JWTs.

signature = Crypto(secret, base64(header), base64(payload))
jbcOUQ2bbiYlfVtprEkaT_S6Y6yQnBDOAKDHIHjvl7g

“Everyone can read my tokens! They can change the claims and grant themselves admin access!”

The first part is true. The second part isn’t. JSON Web Tokens are decodable by anyone. In fact, feel free to copy the following token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxZGZlZThkOC05OGE1LTQzMTQtYjRhZS1mYjU1YzRiMTg4NDUiLCJlbWFpbCI6ImFyaWVsQGNvZGluZ2x5LmlvIiwibmFtZSI6IkFyaWVsIFdlaW5iZXJnZXIiLCJyb2xlIjoiVVNFUiIsImlhdCI6MTU5ODYwODg0OCwiZXhwIjoxNTk4NjA5MTQ4fQ.oa3ziIZAoVFdn-97rweJAjjFn6a4ZSw7ogIHA74mGq0

Part 2: Common Misconceptions, FAQs and Techniques

We’ve discussed how JSON Web Tokens work. The value I hope to provide in this article is far beyond that. I hope you will be able to learn something new from this section where I talk about practical use cases, techniques and common misconceptions when using JSON Web Tokens.

JWTs as Passports

JWTs are often used as a user’s passport. All I need in order to send requests on your behalf is your JSON Web Token. Therefore, it is your (and the service provider’s) goal to ensure the token is kept safe from any impersonator.

Short-lived JWTs and Invalidating Tokens

Short-lived tokens (tokens that expire quickly after they are issued) are highly advised. Some services have their tokens expire as soon as 5 minutes after issuing them.

  • If your token has been compromised, it will expire quickly after and that will limit the time window during which the attacker is able to use your token and perform operations on your behalf.
  • JWTs are stateless. You cannot invalidate such tokens (that is pretty much the only trade-off in using this type of token). Therefore, short-lived tokens are closest we can get to keeping strong consistency over stuff like user permissions and roles.

JWT Advantages and Should You Trust Your Tokens?

JWTs are stateless. That is a blessing and a curse. To my taste, mostly a blessing.

Refresh Tokens

Nicely bridging from the above section. Refresh Tokens are pretty much a must in every system that uses JWTs.

  • Access Token: Your typical JSON Web Token that is sent with every request. Contains the user claim.
  • Refresh Token: This special kind of token is persisted in a database, mostly owned by an Authentication Service of some sort. This is often not a JWT — but rather a unique hash.

Secret VS Private-Public Key (Keypair)

There are two ways to sign JSON Web Tokens. Let’s consider a very common distributed system where we have several services (Auth Service, Warehouse Service, Order Service and Notification Service).

Common Microservices Architecture
  • All services will know the secret. That increases the risk of the secret being exposed or hijacked by an attacker. I mean, when you tell your friend a secret you don’t expect it to be spread around, right?
  • All services technically have the ability to create new tokens — whose responsibility is it to generate tokens? This can introduce semantic problems of ownership.

Where Should I Store The JSON Web Tokens?

This is probably the most common question you will see about JSON Web Tokens on Stackoverflow. I will try to touch it briefly, but would rather refer you to other external resources as I am no security expert.

What If I Want to Encrypt My Tokens Anyway?

In some cases you might want to apply an encryption over your token, to prevent hijackers from reading your claims. This is mostly common in server-to-server communication.

Summary

This is my first post on Medium, and also my best attempt at sheding some light on the whole “JSON Web Token thing”. Hopefully this helped you. I would like to welcome any suggestions and extra information in the comments. I will do my best to keep this article up-to-date with recents developments and techniques.

Useful Resources

Let’s Get in Touch

You are most welcome to follow me here on Medium. In addition, feel free to check out:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ariel Weinberger

Ariel Weinberger

152 Followers

Passionate about education in Software Engineering. Bestselling Udemy instructor. Self-taught Software Engineer and Engineering Manager.