DEV Community

Cover image for JWT for Beginners πŸ”
Himanshupal0001
Himanshupal0001

Posted on

JWT for Beginners πŸ”

In this post we'll discuss about jwt-web-token.

Introduction
JWT is a compact, URL-safe means of representing claims between two parties. It allows you to securely transmit information between a client and a server as a JSON object. JWTs are commonly used for authentication and authorization purposes.

To understand jwt better I recommend to understand how http works and the structure of http.

Main Parts of JWT to understand.

JWT has two major parts to understand.

  1. sign()
  2. verify().

sign()

jwt.sign() is use to generate token in the server. It accepts two parameters.

jwt.sign(payload, secret_key).

A token is nothing but a long hashed string generated by sign function. This string consists of three parts separated by dot[.]

{ headers.payload.secretket}

For the better understanding the above string please see the the below code and then read explanation.

const payload = { userId: 1234, username: 'john' };
const secretKey = 'your-secret-key';
const token = jwt.sign(payload, secretKey);
Enter fullscreen mode Exit fullscreen mode

In the above code payload is the an object including id of the user and username.

You can also send the roles and permission object in the payload to achieve RBAC.

Secret-Key is a long complex string saved in the server secretly that only known by that server.

jwt.sign() function will accept those parameters along with req.headers and hashed the data into a string. Example as below

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6I
kpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Enter fullscreen mode Exit fullscreen mode

That srtring will be returned by the server and saved in localstroage of browser. Later during login server will get that string verify the string and if string is valid , allow the user to login the app.

verify()

The process of authenticating the token received by the client is done by jwt.verify() function. The syntax is as below
jwt.verify(token,secret_key,(err,decode))

It is important to understand that token is coming from the client aka browser local storage, secret key is from server and it return a callback including either err or decoded payload.

How this work is it will get the token that includes headers.payload.sercert_key .

If the hashed secret key is equal to the key present in server, it will authenticate.

See Below
jwt

Top comments (0)