Authorization and Authenticate API NodeJS with JWT

Tram Ho

Hello everyone, after a few theoretical lessons about NodeJS, let’s put it into practice today. And today we will take a step that I think is quite important in the process of building the API, which is Authenticate and Authorization. I will not talk much about these two concepts and why we have to, there have been many articles comparing these two concepts.

In this article, I will use:

  • NodeJS
  • Express
  • MongoDB

Project creation

We will use the express generator to automatically create the app. You can go to the following page for more information: https://expressjs.com/en/starter/generator.html

Run the following command to install express-generator

Then run

to generate the code

You will see that there are a few folders you do not have because you created them yourself, which I will guide in the next section In the project directory, run

and run

to initialize the app. App will be run by default at port 3000. You can create a .env file to change the port or change the default port in binwwww . But the problem is that every time a file modification is made, it will take a lot of work to start again. So please install more nodemon to this action automatically. Details on how to install can be found here: https://www.npmjs.com/package/nodemon .

After you have successfully installed nodemon your package.json file, change start in the script to nodemon ./bin/www

And now let’s start npm again, then try to change a file.

Create DB

Why is mongoDB? Actually, because I have not worked with mongoDB, I want to find out it is plain and simple. Please visit the website https://www.mongodb.com/ , then sign in. After agreeing to the terms and choosing the free package (if you have money). Then go to the settings for sv, in this section you can choose the same level, server location, … Then click Create Cluster

Then there will be a small table with the following steps, complete all the steps, when clicking on each step will have specific instructions so I will not talk anymore.

Details of each step are as follows, except for the first step with brick:

  • Create a user for db (here you will create a user and authorize that user)
  • Set whitelist for IP address (specify which IPs can access, you can also allow access from all IPs)
  • Load sample data (this is okay or not, but I like to look at it 100% so I will do)
  • Connect to your cluster (for this I will guide you in detail below).

There will be 3 options for you to choose from

  • Connect to the mongo shell
  • Connect with your app
  • Connect using MongoDB Compass

Here I will use number 2 and 3, number 2 for me to use in the project to connect, and number 3 as the interface for me to see (similar to how you use phpmyadmin, mysql workbench, …) . First, I will download mongoDB compass. Click on the 3rd option and download it and install it

After the installation is complete, copy the paragraph in part 2, then replace the password with the password of the user you created and press connect in the MongoDB Compass app.

And this is the result. Since I have loaded sample data, I have quite a lot of db, and I have created more db as express to demo

So we have created the DB

DB connection

Now to connect and manipulate the DB, we will use mongoose https://www.npmjs.com/package/mongoose .

First, create a .env file to save these settings, but cannot be saved directly in the code, because if you miss a public repo, it is no different from letting everyone connect to your db. me. Please re-visit mongodb’s website. Please click on the second option in the instructions above. If it’s turned off then you can press the connect button.

Now copy the value of const uri and paste it in .env remember to enter password and dbname

.env

It’s in the app.js file

Now pay attention in the terminal, where sv is running, if you see the line DB Connected , it is connected successfully.

Authenticate

Before authenticate we will have to have a user. So I will create an api to add users first. First let’s create a model

models/User.js :

We initialize a schema and condition each key in it.

Because there are conditions, when there is a request to send, we will definitely have to validate, mongoose also supports validate, but I will not use it but will use a Joi package, You can learn more about this package, I will don’t go into detail

validations/auth.js :

Create more routes/auth.js file

And to use it, in app.js will add the following:

For a little explanation, at first, if there is an error, I will return 402 and its message. You can make the console.log error clear, or you can log the registerValidator(request.body) to see all the returns. To be able to use it in postman you use

to make it easier to see. Now try to open the postman and create test accounts that don’t match the validation rules

As you can see the email has been reported in the wrong format. Returning to any code, then you can see that I will check if the email exists, this is of course because I do not want to exist 2 identical emails in my system. Next, I have encrypted password, the lib I use is bcryptjs . Finally, save the user and send that information up.

So we have successfully created the user

After we have an account, we have to log into the system, right

Return to routes/auth.js file

Now let’s create an api to get the users list

routes.users

app.js

And here is our users list

Wait, why can you use the api so easily, this is so wrong. And that’s why we’re coming to the next one

Authorization

Basically we will create an authentication token, each request that the user submits must be accompanied by that token, if the correct token, the user can call the api that we require to authenticate. And we will use JWT https://www.npmjs.com/package/jsonwebtoken .

In the first place to create tokens, each time a user logs in, we will create a token for that user. Now we will have to fix the login functionality a bit .env

routes/auth.js

You will see that after the validate is complete, I will create a token based on the user’s id, then use token_secret , token_secret extremely important because if the user information is revealed, the token can not be stolen immediately because it remains. token_secret . You can create any string of string, here I just write somethingrandom but I even type a miscellaneous string r encode it: v. And the last option is the customizations you want to add, here I will set the token expiration time to 1 day.

Next, let’s create more middleware to authenticate api

middlewares/verifyToken.js

Here I will check in the auth-token in the header (this can be whatever you set, do not set it with the default one). If there are no tokens, 401 will be returned, but if there are, but the token does not match the token, it will be 400.

Now in routes.users will add the middleware:

Now try to access it again

Now you can’t, wolf. If you want to be able to use this api, please login again. Now after logging in again, there will be 1 token for you, or copy that token and put it in the header. Key: auth-token, value will be the token you copy it

That’s it, hope this article will help you somewhat

Here is my repo if you want to review the code: https://github.com/duongmanhhoang/demo-node-js

Share the news now

Source : Viblo