Zero to Hero – Node.js (part -6) – Secure REST APIs via JWT
In the previous blog, we worked on exposing CRUD operations via REST APIs. But, there was something missing, something very important.
YES!!!, you got it right. I’m talking about Security. We don’t have any mean of authentication and security.
Traditionally, developers use method like cookies and sessions with user authentication. But still, that is not too secure. There are some savior like JSON Web Token(JWT) . JWT based authentication is simple and robust. And we have jsonwebtoken library in node inbuilt for us.
Before diving in for more in our coding, let’s first understand our project structure via below info-graphic
(assuming server.js
is our entry point). You will find this similar to our previous post, in fact, this is extension of previous post, so you can re-use the same application for this blog.
We will use the previous application that we have built. We will just add other required stuff. For that, execute below command:
npm install bcryptjs jsonwebtoken
express-validator@5.3.1--save
bcryptjs
is used to hash the password into the secure string and jsonwebtoken
will be used to generate the secure and expirable token. express-validator
is an npm library use to validate the body of the POST request.
So, let’s rock.
Open local.js
which is inside configs/config/
and paste the below code. Please replace secret-code
with any code you want.
app.js
is 99% same as before with one extra import of express-validator
. Change code like below:
In model, we will have username, password and email for now. you can have more information if you want in your model. For sample:
In this blog, we will have another segment as our middleware
. In this, we will code our validation
as well as authentication
areas.
Create middlewares
folder in root structure and create validation.js
and authgaurd.js
.
In validation
, we will validate the required properties of the POST body like username, email, and password. Sample code like below:
In this file, we are importing check
from express-validator
which provides various powerful functions. Rest fo the code is self-explanatory.
In authgaurd.js
file validates the token for all the restricted API before performing any action on the requested data.
In this file, we are using the jsonwebtoken library with our already defined secure string in the local.js file to secure node.js REST API.
First, we get the token from the headers of the request and then validate it with our secure string. If the token is valid then it processes the API otherwise return a response with Invalid Token message to the client.
Token-based authentication is very helpful to secure node.js REST API. Due to its easiness and security, these days developers use mostly token to secure their API’s from the un-authenticated users.
Sample code as below:
In our Services
module, we will create another folder named auth
. Inside it, we will create auth.js
file, which will export 2 main functions names register
and login
.
register
function will be used to register a user by validating minimum requirements like email and password. After that, these values will be saved in our MongoDb.Also, validation of requested body will be done via help of validation middleware. If the body is valid then we check that if user email already exists or not, if the user email already exists then we send a response back to the client with the HTTP status code 409 and a message stating that email already exists otherwise create the user and send a successful response to the user.
login
function will be used to log in the user and give him/her permission to use our API by generating the token.
Sample code like below:
I’ve created full project and posted it on github, fork it If you want. Changes in other files are very simple and I want you guys to figure it out where are the changes has been made. If you still need, please comment out and I’ll share the video where I’ve explained all.
0 thoughts on “Zero to Hero – Node.js (part -6) – Secure REST APIs via JWT”