Hey all, today we are going to learn about the emplimentation of json web token in nodejs. And also explain in detail what JSON Web Token is and how it can be userd for the user authentication.
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.
JSON Web Tokens consist of three parts which contain encoded data, separated by dots (.), which are:
Header: It consists of two parts, the token itself and the signinng algorithm being used such as HMAC SHA256 or RSA.
Payload: It is the second part of the token in which we can store additional data as per the requirement like we can add here the users id, email and other data we need to pass from client.
Signature: It is created using encoded header, encoded payload, a secret, the algorithm specified in the header, and sign that
Therefore, a JWT typically looks like the following.
aaaaaa.xxxxxx.iiiiiiiiiii
Now lets discuss the emplimentation in our nodejs app.
package.json
In the above file we have our basic dependencies of the demo which we are going to create . Now we will set up our mongodb set up, so let's have a look on db config file
In the above file we have set up the db config.
Now let's discuss the routing part where authentication related task performs:
routes/apiRoutes.js
In the above file we have set the authentication related task, And in the constant appRoutes we have two keys, first public routes in which we pass the api methods which don;t need any authentication and in the second key userRoutes we have stored the name of apis which needs the authentication. And below jwt authentication works accoringly so that jwt will be checked in apis which are stored under userRoutes key.
These were the main points regarding the JSON Web Token, full working source code can be downloaded from this site. Let's have a look how we can check the emplimentation in the api with the screenshots of postman.
1. sign-up(header passed in below api [Content-Type:application/json])
User has been registered successfully. Now come to the next step where user will login to get the JSON Web Token(header passed in below api [Content-Type:application/json]).
In the above screenshot we can see token has been returned from the login API. Now in the next api where jwt is authenticated to complete the request.( header passed in below api [Content-Type:application/json,
x-access-token:*************************])
Pretty cool! Finally, our task completes here.
That’s all for now. Thank you for reading and I hope this post will be very helpful.
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.