How client-server talk securely?
Tags: programming, tutorial, webdev, javascript
Published: 2022-09-21 10:45:14

## Ever wondered 
- how we allow user to logged in and 
- How your Instagram reels is fetched
- Why Firebase and third party keep telling to save tokens
- How frontend and servers talk each other securely.

Well, this question arrives in my mind way back. When I was new to the servers and client, I always use to think how they even talk to each other and who make them talk?

## Not a two-way conversation
But we have a culprit right under the nose.
Since our world is full of non-sense and unwanted species so how come software development can be spared from the attackers.

Its quite easy to give connection between client and server it's just two-way connection or conversation. I ask you something you reply to me directly.

Similarly, the client and server can put a connection session between each other and world would have been a simple place. 


## Unfortunately it's not
The attackers arrives in the first place. Now when client and server have good two-way conversation these attackers nose is right in between. 

Listening them is not too risky but these attackers have started stealing the important key points from the conversations. 

For example email, password and other details from the website are being stolen by the attackers. 

## Real-world story
Read this interesting story [how the person win $100,000 by finding bug in authentication process of Apple](https://www.zdnet.com/article/researcher-lands-100000-reward-for-sign-in-with-apple-authentication-bypass-bug/).

A lot of importance have to give to the conversation happened between the client and server. 

The loss of any key-value pairs might be the vulnerable to who knows what, don't ask me I also don't know(still researching about it). 


## World evolves
Now the world have evolved over the time 

> As Elon musk says - 
> Technology doesn't grow over the time, its the people behind it working extensively hard to make it grow

and in few years down the line in early 20s, we got the new way of having conversation between client and the server.

## Tokenization
The concept begins in 2001 to store credit card crucial information. Before this the credit card and other financial sensitive information were stored on server itself which make them vulnerable to be stolen.

Basically before tokenization concept, the server stores the crucial information. So one attack to the server will help the attackers to stole as much information/data they want. 

## Example
The user PAN card details were stored directly on the server initially but now we store only tokens and via the tokens the PAN card details are send over the conversation between client and server.

## Tokens
Tokens are just a hashed strings created using certain types of algorithm. Most of the tokens are just string containing no data the corresponding data related to the token is stored in the token vaults or database. Tokens and the related data can only be accessed via mapping them together in the vault.

But nowadays tokens have become more advanced and stored the additional information that is encrypted. The token have to be decoded to extract that information and it's not that simple. To decode the token one has to understand the algorithm used behind it in making. 

Most of the tokens used 2-way process to decode meaning even if the attacker get the token somehow he will only be able to extract the information if he have the token creator private key also called as signature.


## JWT 
JSON Web Token or JWT is introduced after all other tokenization concepts but I am covering it because it's been widely accepted and used in the industry.

** Defination **

![JWT website scree shot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zpaamstcz936etrp1vf.png)

This is the defination given by JWT itself.  

Open standard means that JWT is easy to use and incorporates in your development process. Widely accepted and kind of open-source to be used by anyone in the world.

## How JWT is made

JSON Web Token it made of 3 parts.

**Header** - Defines the type of token and the signature used in the token

**Payload** - Contains the user credentials or additional data 

**Signature** - Verify that sender is the only one who sends the token


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


## Heres how JWT works?

- Whenever we want to login from frontend we send a request to the server with the credentials such as email and password in most general case. 

- Then the server verify the user credentials and if those credentials are valid it create the JWT token using sign method. 

> Note that - JWT sign method need the signature as the private key and the user credentials payload create the token.
 
- The server sends the token to the client and giving indication that user is valid. Client save this token for further conversation with server. Understand how this works now -

- Every time now client want to talk to the server it has to send that token before initiating the call. 

- Next time, when client wants to request same user data such as profile image, phone numbers from the database. The client will send the JWT to the server. Server then decode and `verify` this JWT using verify method.

- JWT `verify` method returns the payload as the response and this payload is then cross verified with the payload send by the client to final check and double authenticate the user account. 

- If everything goes good server allow the client to talk/connect by sending the required data such as phone number in our case.

The best image representation 

![How JWT works image explanation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7qcck0wcb9vee3jpeiol.png)

## Creating JWT token

It's not a rocket science, in fact it's just few lines of code.

```
jwt.sign({ email: email },process.env.JWTSecretKey,{expiresIn:'14d'})
```

Here `sign` method has given an email and secret key to create token and lastly we have expiry date or time period. 

Wait for few minutes because to understand why that email is important to create token.

### Decoding JWT token
When client sends back the token to the server, server will decode it or verify it.

We provide 2 way process to verify 
- First we use verify method to decode the token
- Then we cross that email return after decoding is same as the email pass during creation of a token

```
const token = headers.split(" ")[1];
    const jwtVerifyToken = jwt.verify(token, process.env.JWTSecretKey);
    if(jwtVerifyToken.email !== email){
        res.status(404).json({ success: false, message: 'Invalid token'});
    }
```

First the token is send from the client in the headers, followed by verifying of token and lastly we cross check that token is creating using same email as passed initially.

In this way, we have added 2 way protection to the tokens. 
Every crucial conversation between client and server is handled using these tokens. 

## Use case
In the client side we even use the tokens to manage user sessions. For example, storing tokens in the cookie and everytime user comes back to the website we check the token validity and if its expired we throw the user out of the application asking him to logged in again.

Tokenization concept is used in Authorization and Information transmission too. 

## Alternatives
It's not like JWT is the most secured and top-notch token concepts. We do have other alternatives such as 
- OAuth
- Passport
- AuthO

You can google them....

But what's important is the secutiry, community, and easy to use. JWT is quite easy to use with express.js or reactjs in both client and server side.

It's just a bunch of javascript algorithms fused together to generate hash string.

## Conclusion
Here are the references I have read to understand tokenization, JWT and many more.
[Introduction to JWT](https://javascript.plainenglish.io/most-secured-authentication-via-json-web-token-a45ae52a76df)
[JWT website](https://jwt.io/introduction)
[Tokenization](https://www.tokenex.com/resource-center/what-is-tokenization)

Keep developing 
Shrey
[Youtube](https://www.youtube.com/channel/UC6I-Tz6QwYbJpoIK7l0NtXA)