Complete Guide to JWT

20 Nov 2021
Complete Guide to JWT

Modern internet requires an information flow between applications. JSON Web Tokens are a very compact way to carry information. JWT is most commonly used for authentication in applications where receiver can verify the request from sender. In this article, we will learn about JWT in depth covering it’s structure and when to use it. In future articles, I’ll be covering ways to implement JWT in your applications.


What is JSON Web Token?

In a more formal way - JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA. Thus the information can be verified and trusted because it is digitally signed. But, JWT is not encrypted so should be used over HTTPS connection.

Structure of JWT

JSON Web Tokens (in compact form) consists of three parts which are separated by dots. (.)

  • Header
  • Payload
  • Signature

A JWT typically looks like the following -

<base64url-encoded header>.<base64url-encoded claims>.<signature>

JWT Structure

Let’s learn about each component to understand JWT better.

Header

The header includes metadata information about the JSON Web Token. In contains two parts:

  • typ - Type of the token: JWT always
  • alg - Signing algorithm being used. Eg. HMAC SHA256 or RSA.

The header includes claims about the token. We’ll discuss more about claims in the next section. This JSON is Base64Url encoded to form the first part of the JWT.

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

The second part of the token is the payload (also known as body) contains the claims. Claims are statements about an entity and additional data. Claims follow the standard key-value pairing that you see in dictionaries and JSON objects.

There are three types of claims:

  • Registered claims - These claims provide a starting point for a set of useful, interoperable claims. Eg. “iss”, “sub”. You can explore other registered claims here.
  • Public claims - These claims are available to public and need to be registered in the IANA JSON Web Token Claims registry.
  • Private claims - these are custom claims to share information between two parties.
{
  "sub": "123456",
  "user": "Mohit Khare",
  "subscriber": true,
  "exp": 1637421361
}

In the above payload, we’ve defined three private claims with an expiry time that share specific information between server and client for an application. Again, this JSON is Base64Url encoded to constitute the second part of the JWT. Also, the payload of any JWT by default can be decoded by anyone.


Signature

The third part of the JSON web token is the signature. Signature helps in ensuring that a given token wasn’t changed or manipulated by some middleman, since JWTs are digitally signed that requires either a secret or a public/private key pair.

To create the signature part you need four components that is then required to be signed.

  • Base64 encoded header
  • Base64 encoded payload
  • Secret
  • Cryptographic algorithm
signature = CryptoAlgo(base64(header), base64(payload), secret);

Here is an example of how we can create a signature.

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret);

Finally we have our JWT created.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTYiLCJ1c2VyIjoiTW9oaXQgS2hhcmUiLCJzdWJzY3JpYmVyIjp0cnVlLCJleHAiOjE2Mzc0MjEzNjF9.QQskwkC3f9UbomHQqdxel5FDH8jIsLvokC5AsPcP-Tw

When to use?

  • Authorization - Each client request includes JWT that can be used to control access to routes and resources.
    • The server generates a token that certifies the user identity, and sends it to the client.
    • The client will send the token back to the server for every subsequent request that required authentication, so the server knows the request comes from a particular identity.
    • Once the request arrives at server. It looks for the token and verifies it.
  • Information Exchange - safely transferring data between multiple servers in your application.

Points to remember

  • JWT is not encrypted. You can check the payload for the JWT we created on jwt.io
  • JWT are stateless and shouldn’t be stored in database. Mostly clients store it in local storage but that’s really bad way to do it. One feasible way could be to store JWTs inside an httpOnly cookie.
  • JSON web tokens should have an expiry time. In modern applications, once the JWT is expired. a persisten refresh token can be used to regenerate JWT.
  • One should not use JWTs as session tokens. JWTs are relatively large that results in a ton of overhead per request.

Resources


Summary

In this article, we covered the basics about JWT including its structure. We also covered some key things to remember when working with JWT. Stay tuned for another tutorial where we’ll implement JWT using Go in a real world application.

I hope you learned something new. Feel free to suggest improvements ✔️

Liked the article? Consider supporting me ☕️

I share regular updates and resources on Twitter. Let’s connect!

Keep exploring 🔎 Keep learning 🚀

Liked the content? Do support :)

Paypal - Mohit Khare
Buy me a coffee