# JWT

JWT is a means of representing transfer requests between the two Client - Server parties, the information in the JWT string is formatted in JSON. In which the Token string must have 3 parts: header , payload part and signature part separated by "."

<figure><img src="https://1722711354-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FwNXdoUkfmcozr29fRrfb%2Fuploads%2FNEcqinctjFkBssf3rLGQ%2Fimage.png?alt=media&#x26;token=18d75b34-3bae-434d-ae5d-e86d9fd2a50c" alt=""><figcaption></figcaption></figure>

So according to the above theory, I will have a Token chain as follows:

```
header.payload.signature
```

## Structure of JSON Web Token

As mentioned above JSON Web Token consists of 3 parts, separated by a dot (.):

### 1. Header&#x20;

Will contains what type of token and encryption algorithm

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

* **“typ” (type)** indicates that the object is a **JWT**&#x20;
* **“alg” (algorithm)** defines the encryption algorithm for the string as HS**256**

### 2. Payload&#x20;

The **payload** will contain the information you want to put in the **Token** string such as **username , userId , author , ...**

```json
{
  "user_name": "admin",
  "user_id": "1513717410",
  "authorities": "ADMIN_USER",
  "jti": "474cb37f-2c9c-44e4-8f5c-1ea5e4cc4d18"
}
```

> Note do not put too much information in the **Payload** chain because it will affect the delay when the **Server** has to confirm a **Token** that is too long.

### 3. Signature

This signature will be generated by encrypting the header , payload with a **secret key**, for example:

```
data = base64urlEncode( header ) + "." + base64urlEncode( payload );
signature = Hash( data, secret ); 
```

* **base64UrlEncoder** : header and payload encoding algorithm&#x20;

The above code after encoding the **header** and **payload** using the **base64UrlEncode** algorithm, we will have the following string

```java
// header 
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 
// payload 
eyJhdWQiOlsidGVzdGp3dHJlc291cmNlaWQiXSwidXNlcl9uYW1lIjoiYWRtaW4iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNTEzNzE
```

Then encrypt the above 2 strings with secret **(secret key)** with the **HS256** algorithm, we will have the following signature string:

```
9nRhBWiRoryc8fV5xRpTmw9iyJ6EM7WTGTjvCM1e36Q
```

#### Final&#x20;

Combining the above 3 strings we will get a complete JWT chain

<pre><code><strong>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsidGVzdGp3dHJlc291cmNlaWQiXSwidXN
</strong></code></pre>
