Understanding JWT
Tags: programming, webdev, security, beginners
Published: 2022-06-02 05:05:38

## What is JWT ##
JWT stands for JSON web tokens. It is an industry-standard, for passing user claims between client and service and between services. The claims in a JWT are encoded as a JSON object. A claim is just information of the user which is needed by the server to verify their identity and assign appropriate roles.
A JWT consists of 3 parts

- Header
- Payload
- Signature

#### Header ####
The Header in JWT indicates that it is a JWT token and identifies which algorithm is used to generate the signature. 
```json
{
  "alg": "HS256",
  "typ": "JWT"
}
```
#### Payload ####
The payload contains a set of claims.
```json
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}
```

#### Signature ####
The signature validates the JWT token. The signature is generated by encoding the header and the payload along with a secret and concatenating the two together with a period separator.
```json
HMAC_SHA256(
  secret,
  base64urlEncoding(header) + '.' +
  base64urlEncoding(payload)
)
```

The three parts are encoded and combined using a period separator to form a JWT token. This is what a sample JWT looks like. (The red part indicates the Header, the purple indicates the Payload and the blue indicates the Signature)
![Sample JWT](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uovmafs8gwor67mpea3r.png)

### Why JWT ###
Most of the application we use requires us to be logged in to access some additional functionality. Normally user logs in by giving his credentials. It is not good practice to use the credentials provided by the user throughout the lifetime of the user's session.

Traditionally, the user's state and related information was maintained by servers. They would store this information in external storage like Redis. A session cookie was used to get the user's data from the external storage.


![Session based authentication](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nhitgtcmlzbpd9zrb7rv.jpg)

This solution would still work, but modern applications rely on RESTful services and RESTful services are stateless. They don't store any state information in them. This makes them highly scalable. So JWT was needed. JWT can store the required state-level information in them in a somewhat secure manner. The server will send this JWT token to the client and the client has to send this token in every subsequent request.

![JWT based authentication](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cw8vs40o4q1bjp3rtt7o.jpg)

### What are the pros and cons of using JWT ###
#### Pros of using JWT ####
- Since the tokens contain all the necessary information, you do not have to query the DB all the time
- The server does not need to maintain an external storage to handle users state
- Easy to validate across multiple services. You just have one server which does the authorization and then passes the token across multiple services that require the information

#### Cons of using JWT ####
- If someone gets the JWT, they may be able to impersonate the person
- You cannot store lots of information into the JWT token as it will create a data overload. It is advised to store only the basic information and fetch other data by querying DB as required. Also for web applications, you will use JWT with cookies can store only a certain bytes of data.

### Securing your JWT ###
As mentioned above, if some malicious user gets access to your JWT, they might be able to impersonate your user. So you must be careful when using a JWT.

- Never store JWT in local storage in browser. Any malicious javascript code can easily access this.
- If possible, create JWTs with short life. But be careful, if you invalidate your JWT, your users will be treated as logged off. You don't want your users to be logging in all the time.
- Make sure you use SSL as it will encrypt your network traffic which will prevent your JWT from being stolen by anyone who has access to your network.

### What to do if you loose your JWT ###
A compromised JWT is same as a compromised password. You should follow the same procedure as you do for a compromised password. This might include

- Blocking the user's account
- Asking the user to change his password immediately
- Revoking all permissions from the user

#### How to know if you have lost a JWT ####
Acting quickly on a compromised JWT can be vital in preventing the loss of your customer data. We can do the following to know if we have lost a JWT
- Monitor the client's location. Most likely, if someone has breached your security, he will try to use the token from some other location than the one which your client was using. This can be a good indicator to know that your JWT is stolen. But masking location is a simple task.
- Analyze the pattern of the user. If your attacker has stolen your JWT, he will try to make use of it as soon as possible. So you will have to check the behavior of the JWTs. For example, if a user who normally sends 10 requests per minute, starts sending 50 requests then that is a sign of lost JWT.

As you see, securing a JWT is a complex task in itself and would require a significant effort if you care about the data of your users. That's why it is always advised that you delegate the task of handling authentication to an external service like Auth0 or Okta or FusionAuth. For a nominal charge, these services will take care of all your authentication problems.