Decoding the JSON Web Token aka JWT

Ishwar Rimal
5 min readDec 27, 2023

--

The most common question I was asked in my recent interviews was about Web Authentication. Mostly around Session-based authentication, JWT, how authentication works, and how they make communication over the web safe.

Photo by iMattSmart on Unsplash

In this article, I will be writing about how JWT works, what the different components of JWT are and other topics related to JWT.

What is JWT?

JWT or JSON Web Token is an authentication token that is URL Safe (It is encoded using URL-safe base64 encoding), it’s self-contained (information required to authenticate and authorize a user is contained inside the token itself), and is used as a mechanism to pass data between the server and the client.

JWT token consists of 3 parts :

  1. Header
  2. Payload
  3. Signature

We will discuss more on this later in the article. For now, let’s understand how authentication happens.

In general, how does authentication happen?

As a user, you log in to the client’s website by providing your username and password. The client passes these details to its backend (with some basic encryption) to check if the credentials are valid.

The backend checks with its database for the username and password to check if the provided user exists and if the credentials are valid and if it’s valid, allows the user to proceed further.

For further communications, in a naive way, the client can keep sending the credentials and the server can keep checking it with its database for authenticity. However, this is prone to attack and may not be practical for a larger system.

How does JWT solve this?

(It’s important to note that every server that uses JWT is provided with a very unique secret key which is called the “Secret Key” of course.)

Once the user is verified for the first time (as discussed above in how authentication happens) by the server, the server uses this Secret Key to create a unique JWT token, which will be used for communicating further with the client (So that on every request, credentials need not be passed).

The JWT consists of 3 parts: Header, Payload, and the Signature.

What is a Header?

The header contains information about the type of token (typ which is always JWT) and the hashing algorithm (alg) used for creating the signature.

Example:

//header with HMAC SHA256 algorithm
{
"alg": "HS256",
"typ": "JWT"
}

//header with RSA SHA256 algorithm
{
"alg": "RS256",
"typ": "JWT"
}

//header with no algorithm
{
"typ": "JWT"
}

What is a Payload?

The payload of a JWT contains the actual data which needs to be transmitted. It’s essentially a JSON object that consists of user-specific information as a set of claims or assertions (e.g. the user, device, or application it represents).

Example:

{
"iss": "https://example.com",
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"exp": 1516239032,
"roles": ["admin", "editor"]
}

Note: The claims in the payload can be classified into three different categories — registered, public, and private. The registered claims are defined by the JWT itself and include information like the issuer (“iss”), subject (“sub”), expiration time (“exp”), and issue time (“iat”) of the token. The public claims are defined by the user for use in their applications, and the private claims are custom claims defined by the users and are not meant to be shared across applications.

What is a Signature?

The third and final part of the JWT token is the signature. A signature is a key or a token that is created by taking the header and payload and appending it with the secret key, which is then hashed using the hashing algorithm provided in the header:

signature = hashing(encoded header + payload + secret key)

Once the server generates a JWT, it sends it to the client, and the client stores it locally, typically in the browser’s local storage or in a cookie.

Now it’s the client’s responsibility to send this token in the subsequent requests to the server.

You will find the JWT token sent in the request header in the following format:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikpva

How does the server validate this token?

Once the server receives the token from the client, the server verifies the signature by recomputing it based on the same algorithm and secret key shared as before.

After verifying the signature, the server can be sure that the token has not been tampered with and that the data contained in it is authentic.

What happens if the token is tampered with?

If the newly constructed signature does not match the signature passed by the client, the verification fails, this means that the token has been modified after it was issued, and it should be rejected.

Also if the token has an expiration time defined in its claims and that time has passed, the token is considered to be expired and invalid.

In such cases, it’s typical to return a 401 error response to signal to the client that the request is unauthorized, indicating that the client must obtain a valid token before retrying the request. Hence the client will redirect the user to the login page.

Is it always required to reauthenticate in case of an expired token?

It depends on the implementation of the JWT. If a refresh token is been used, the user does not always reauthenticate when the token is expired.

A refresh token is a special type of token that is used to obtain a new access token on behalf of the user without requiring them to re-authenticate

Refresh tokens are typically issued alongside access tokens during the initial authentication process and are used to provide a persistent mechanism for obtaining new access tokens as the old ones expire.

When the access token expires, the client sends a request to the authentication server with the refresh token, and the server returns a new access token that can be used for further requests.

Note: Remember that even a refresh token has an expiration time.

What are some disadvantages of JWT-based authentication?

  • JWTs can be vulnerable to CSRF attacks (read more).
  • JWTs are less suitable for revoking user access to a single device. Once a JWT is issued, it remains valid until it expires, and it cannot be revoked early from the server.

Related topics:

  1. Decoding session-based authentication. (read here)
  2. Server-side vs client-side cookies. (coming soon)
  3. What are auth servers and why it’s required. (coming soon)

I hope you found this article useful. I would love to hear your thoughts. 😇

Thanks for reading. 😊

Cheers! 😃

If you find this article useful, you can show your appreciation by clicking on the clap button. As the saying goes, ‘When we give cheerfully and accept gratefully, everyone is blessed’.

--

--

Ishwar Rimal

Senior FrontEnd Engineer at Intuit. 8 years experience. I write articles on JavaScript, React, Web Optimisation, Startups, Work Life Balance, etc. ❤️ JavaScrip