Demystifying JSON Web Token (JWT): A Practical Overview
Tags: webdev, javascript
Published: 2023-11-23 09:09:42

## Introduction

After reading this article, you will learn what JWT stands for, what are its parts, and what is its use in communication between client and server. You will find the mechanism of JWT simple and useful!

## What is JWT

JWT stands for Jason Web Token and the main purpose is to enable secure data transmission between the parts. They are usually the client and the server. JWT can be passed in the header of HTTP request, as a body parameter of POST request, or parameter in URL request but it is less common and secure. The practice is to pass the JWT in the `Authorization` header. It is the most secure way because it is prevented from being logged which reduces the risk of exposure. Here is a simple example:

```jsx
fetch('https://example.com/endpoint', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${YOUR_JWT_TOKEN}`
  },
  body: JSON.stringify(data)
})
```

You can see that JWT is sent as Bearer token. Bearer token is type of token primarily used for authorization and it is usually associated with OAuth 2.0. 

## Purpose of JWT

JWT token can hold information that is encrypted and is available right away. It means it will avoid extra calling the database. Usually JWT has information about the user but it is also used for **authorization**. After login, calls of APIs must have access token which is the JWT. Then the user is allowed to make such a call.

Now, let's cover parts of the token. JWT consists of header, payload, signature. 

### Header

Header keeps information about what type of token it is and how the JWT is encoded. It can be for example:

```jsx
{
  "alg": "HS253"
  "type": "JWT"
}
```

It is the first part of the JWT. Here is base64url encoded:

```jsx
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
```

The client is not doing a lot with the header. It sends the JWT with the header to server and server then takes the alg information from header to verify signature.

### Payload

Payload part holds the data about the entity, usually the user, and other metadata. Data is so cold `claims`. This is an example of a simple payload:

```jsx
{
  "sub": "1234567890", // subject, usually the ID
  "name": "Adam",
  "admin": true, // custom claim
  "iat": 1516239022 // issued at, timestamp when the token was created
}

```

Payload is not encrypted, sometime is it not even encoded therefore it should not contain any sensitive information.

### Signature

Signiture is the last part of the token. It is used to verify that the sender of the token is who says it is and that token wasn’t changed along the way. Steps to create a signature are: Firstly, you have take the encoded header, the encoded payload, a secret, algorithm specified in the header and sign it. Pseudocode to create a signature can look like this

```jsx
// pseudo code
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)
```

The purpose of the signature is to secure the token agains uncotrolled changes and to verify the sender of the JWT is who it says it is.

## Practical example

And now we can go step by step through to real scenario how is JWT treated during the HTTP call and authorization.

1. **User Login**
First step is the user login. He fills the credentials on the login page and sends them to the server.

2. **Verification**
The server validates the credentials against the database and if the login is successful then the JWT is created.

3. **JWT Creation**
As we described in the previous chapter, JWT contains payload with user information and claims. The server uses secret to sign the JWT that ensures that the JWT hasn’t been transformed on the way from the client.

4. **Token Transmission**
Then the server sends the token to client usually as response to the HTTP request.

5. **Client Stores the Token**
Client might to store the JWT in the browser’s local storage, cookie or session storage.

6. **Subsequent Requests**
Then with every subsequent  request to the server, JWT is usually included in the header of HTTP request as `Authorization: Bearer <token>`

7. **Server JWT Validation**
When the server receives HTTP request with the token, then it validates the signature to ensure it is legitimite. If the token is valid and not expired then the server returns requested response.

8. **Token Expiration and Refresh**
JWT often contains information about expiration time (exp claim). Token can’t be used when is expired. Application may use refresh token mechanism to issue a new JWT without need to login again.

## Conclusion

In summary, we've covered the building blocks of JSON Web Tokens (JWT): the header, payload, and signature. We've also highlighted how JWT serves as a handy tool for passing information between the client and server. Importantly, when included in a request's header, JWT acts as a way to authorize and secure the communication between the two. It's like a secret passcode that ensures smooth and safe data exchange in web applications.