BrainBite logo
BrainBite
Contact

What is JWT (JSON Web Tokens) and What's the need of it?

What are the advantages of using it? How JWT works?.

4 min read

Hii 👋

JWT(Json Web Token)

In this blog you will get enough information to start with JWT. Before going to deep dive into what is JWT and its implementation. Lets see " why JWT is important to use? ".

User authentication

There are two main ways to get the job done sessions and tokens. The traditional approach on the web are cookie-based server-side sessions.

Session Based Mechnism

1. The process begins with a user filling out their username and password and then submitting it to a server.

2. The server then validates it by creates a session in the database then responds with a session id to client.

3. The session id will be saved in the browser's (cookie jar). Session id will be sent back to the server on each request to validate the user.

4. Server wil validate the session id and will send response accordingly.

Disadvantage of using the session based authentication

You'll need to store the session ID in a database or keep it in memory on the server. Whenever a user requests to access some information, the server needs to authenticate the token first from the database, which adds overhead to the server. Additionally, storing the token somewhere makes it vulnerable to an attack known as cross-site request forgery. This brings us to token-based authentication, which solves this problem.

What is JWT (JSON Web Tokens)

JWT is a token based authentication.

Defination - JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

In JWT, the process begins the same with the client sending its login details to the server. Here, instead of storing a session ID, it generates a JSON Web Token. The token is created with a private key (which can be anything chosen by the server) on the server side. This newly created token is sent back to the browser, where it's typically kept in local storage for future requests.

The token will be added to the Authorization header prefixed by "Bearer" when calling APIs. The server then only needs to validate the signature. There's no need for a database lookup or storage elsewhere in the infrastructure.

How validation happens?

You have two APIs: login and getData. When a client logs in using their credentials (e.g., ID and password), the server will use those credentials (let's assume just the ID for this example) and a private key to generate a token.

const tokenPayload = {
    user_id: user.user_id,
};
const token = jwt.sign(tokenPayload, 'secret token',{expiresIn: "2m"});

This token is then sent back to the client. The client stores this token in their local storage.

Now, when the client calls the getData API, it has to pass the token along with the request. The server receives this token and uses its private key (which it already possesses) to verify and decrypt the token.

jwt.verify(token, "secret token", (err, user) => {
    if (err) return res.sendStatus(403);
    req.userID = user;
    next();
  });

By decrypting the token, the server retrieves the credentials (ID) that were used to create the token in the first place.

With the ID obtained from the token, the server can directly check whether this ID exists in its database. If the server finds the ID in its database, it will retrieve the corresponding information. Otherwise, the server will return an "credentials invalid" error.

Thanks for reading my blog. I think now you can answer the questions realated to JWT. To Know how to implement the JWT you can read blog.

Feel free to reach out if you have any questions or need further assistance!