Nodejs authentication - jwt token - Part2
jwt stands for json web token. As the name suggests jwt provides a token to authenticated user on login or register which can be used to give access to private routes to user.
Implementing jwt
In the last article bcryptjs was used to encrypt user password and return the value upon login. Let’s now implement jwt so that upon login/register user will get a token in return which can be stored and sent along as authorization header to access to private routes.
First let’s install jwt- npm i jsonwebtoken
. Now modify users.js
to use jwt.
jwt.sign()
method is whats important here. It takes in a payload which can be user id
, email
or the whole user
object. Then it takes a secretkey
variable which ideally should be stored as environment variable. This key can be any random value but it needs to be same throughout the app. We can add options
like expiresIn
in here. And lastly a callback function which returns a token based on the payload and secret key and options provided.
By using jwt now we get a more secure data in return except for plain user info. Let’s create a secure route so that user can access it only when a valid token is provided. Modify the routes/index.js
file.
Here we are using the jwt.verify()
method to check whether the token provided in the header is valid. We have to provide the same secret key as an argument. If the token is valid we get the info stored in the token which proves that we are authorized.
So, this is how we can use jwt for authentication. There are more methods and options we can add with it but knowing sign
and verify
method is enough for simple authorization.
But now the problem arises that we have to check authorization using jwt.verify()
in all routes which can be a problem for large application. It would be nice if we could use a middleware which handles all of these for us and that’s where passportjs comes in. Check out the third part of this article to know how to use passportjs along with bcryptjs and jwt for authorization.