JWT explained in 4 minutes (With Visuals)
Tags: webdev, javascript, tls, node
Published: 2024-02-24 15:51:40

{% embed https://youtu.be/0WH9oiYMS3M %}

# Introduction

JWT authentication and session authentication are ways to authenticate users of your web app.
In this article we will explain the details of JWT, its structure along with its pros and cons.
JWT stands for **JSON Web Token**, and it is a commonly used stateless user authentication [standard](https://datatracker.ietf.org/doc/html/rfc7519) used to securely transmit information between client and server in a JSON format. 
A JWT is encoded and not encrypted by default. 
It is digitally signed using a secret key known only to the server. 
It can be encrypted, but for this article we will focus on signed non-encrypted tokens.


# Structure of JWT

A JSON Web Token consists of 3 parts separated by a period.
The header, the payload, and the signature.
Each section is base64 encoded.


![JWT encoded structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ur5abitdnsxnmlpzs2pk.png)


### Header

The header consists of token type, which is JWT, and the signing algorithm used, such as HMAC SHA256 or RSA.

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

### Payload

The payload consists of the claims. 
Claims are statements about the user, and additional data.
For example, we have the time the token was issued at.
We also have its expiration time, because tokens should expire.

```html
{
"iss": "example_issuer",
"sub": "user_id123",
"exp": 1644768000,
"iat": 1644744000
}
```

### Signature

The signature is most important part of a JWT. 
It is calculated using the header, the payload, and the secret, which are fed to the signing algorithm to use.

```html
signature = HMAC-SHA256(base64urlEncode(header) + "." + base64urlEncode(payload), secret_salt )
```

![JWT Structure Decoded](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o72ktulq29hondu66rbe.png)


# Steps

The steps involved in a typical JWT authorization flow are as follows:

**1- Authentication:** The user signs in using username and password, or using for example Google or Facebook.
The server verifies the provided credentials.

**2- Token Generation & sending token to client:** The server will generate the JWT and send it to the client, which stores it for future use.

**3-Sending the Token to server:** When the client wants to access a protected resource on the server, it sends the JWT in the Authorization header of the HTTP request.

```html
axios.get(URL, {
    headers: {
        'Authorization': 'Bearer ' + token,
    },
})
```

**4-Verifying the Token:** The server receives the request and verifies the JWT by checking its signature using the secret key that was used to sign it. 
If the JWT is valid, the server extracts the information contained in it and uses it to determine what actions the user is authorized to perform.

**5- Authorizing the Request:** If the user is authorized to access the resource, the server returns the requested data. If the user is not authorized, the server returns an error message.

![JWT Flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/igvye1880i9491jbz525.png)


# **Advantages**

![JWT Advantages](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mg76chqzkpoz8pb7o9dt.png)

- Lightweight

- Portable: can be processed on multiple platforms, web and mobile.

- JSON parsers are common in most programming languages.

- Protected against tampering because of the secret key stored on server side.

- The server does not need to store any session information, because of the stateless nature of the JWT token.



# Disadvantages

![Disadvantages](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmvzoi46hyd3wt8t6hpp.png)

- On server side, should manually mark non-expired JWT as invalid on logout.
A JWT can still be valid even after it has been deleted from the client. 

![JWT still valid](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fdrm27cehhd0bck5djzt.png)

A method used is token blacklisting, which involves maintaining a list of invalidated tokens on the server side, preventing their reuse for authentication.

![Token blacklisting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wultrfhdmneg7yoqtyv8.png)

- For signed non encrypted tokens, we should not store sensitive info because JWT is protected against tampering but can be decoded and read by anyone.

- Can provide full access if intercepted. That’s why JWTs on client side should be stored somewhere secure, for example in the browser in an HttpOnly cookie.

**My other articles:**

- [OAuth 2.0 Explained In Simple Terms (With Visuals)](https://dev.to/jaypmedia/oauth-20-explained-in-simple-terms-with-visuals-30he)

- [What happens when you click a URL - DNS Lookup, TCP Handshake & HTTP (With visuals)](https://dev.to/jaypmedia/what-happens-when-you-click-a-url-dns-lookup-tcp-handshake-http-33i1)

- [TLS Certificates 📝 - Simplified for web developers
](https://dev.to/jaypmedia/tls-certificates-2902)

{% embed https://youtu.be/iEXD7DB3QRQ %}
{% embed https://youtu.be/dd8cCt9wMh8 %}
{% embed https://youtu.be/1XbvNSwvkAs %}