JSON Web Token(JWT)

JSON Web Token(JWT)

Internet standard for creating data with signature and encryption

Introduction

Json web tokens is the method using which information can be shared between 2 parties in a secure way. It allows you to decode, verify and generate JWT.

What is Authentication?

Authentication is the method of proving if something is genuine, or in computer terms it means proving the identity of a user for requests.

for eg: I open my google mail box how does google know who's mail to show here the user needs to confirm his identity either by entering their email and password.

Why do we need tokens?

It is frustrating when a user always has to enter their email and password. This is where cookies come in handy, they hold the user information and sends it to the mail server which then gets to know about who the user is and can send the respective mails.

But is it safe to store user data on the browser?

Answer is no, as it can be manipulated easily, the cookie can be changed to any users data if stored as it is, this is why tokens are used. There are encrypted cryptograpically soo as to prevent tampering and extraction of information.

Here maybe cookie = {email: "abc@mail.com" }

This can be fixed by sever making unique ids for each user and sending and receiving on each request but alot of space is wasted on the server side for this. This is why JWT is preferred.

How does Json Web Token work?

Json Web Token has 3 main parts demonstrated using 3 different colors and seperated using a dot in the token in the above image.

  • Header: This holds the information on the algorithm used to encrypt the user data which is base64 encoded.

  • Payload(user data): This holds the actual user data which is base64 encoded (can store userId: "inc-0011").

  • Verify Signature: This is where all the magic happens, consider

      const info = base64Encoded(header) + base64Encoded(payload)
      const secretKey = "thisIsAVeryBadSecret" //use secret of length 32 or more
      const signature = HS256(info + secretKey) // use the algorithm HS256 to encrypt it
      // append the info and signature and send to user
    
      const finalToken = info + signature
    

    Above code shows the internal working of how a token is created

Now you may ask, ok we got the token how is it secure?

Soo next time the user sends a request this token is sent the header as a bearer token as bearer token: { "authorization" : "bearer "+finalToken}

Now this is how the server responds to the request

const token = request.header.split(" ")[1]
const tokenParts = token.split(".")
const tokenHeader = tokenParts[0]
const tokenPayload = tokenParts[1]
const tokenSignature = tokenParts[2]

if(HS256(tokenHeader+tokenPayload) === tokenSignature){
    // this suggest the token is valid and has not been tampered with
    const userData = base64Decode(tokenPayload);
    return userData;
}else{
    return throw new Error("Not Authenticated")
}

This is how a jwt authentication works and prevent any tampering, if any letter is changed the whole token becomes invalid.

Downside of JWT can be we can not store large amount of data in the payload as the limit for headers size is 8kb in a http request.

Conclusion

JSON Web Tokens (JWT) provide a secure method for sharing information, ensuring data integrity through cryptographic encryption. While efficient for authentication, JWTs have payload size limitations, yet offer robust security and streamlined data exchange.

Note: above code can be implemented using jwt functions

  • const token = jwt.sign({ userId: user.id }, secretKey, { expiresIn: "1d", });

    parameters : payload, secret key in server and time to live

    used to generate token

  • const tokenPayload = jwt.verify( token, secretKey );

    const userId = tokenPayload.userId;

    parameters: token from user, secretKey in server

    used to decode and get user information

for more information: visit JWT Offical Page Here

Note: for any corrections do reach out to me using my socials present in the navbar.