Auth with NodeJS, Express, Mongoose and JWT
Nội Dung Chính
Auth with NodeJS, Express, Mongoose and JWT
Matteo Lobello
·
Follow
Published in
ITNEXT
·
·
Sep 24, 2019
3 min read
—
Security of your database is one of the most important factor to consider when building a new project.
There are several ways to implement a solid authentication system.
In this article I’ll show you how to make one using JWT, completely from scratch and without the need to use third party services.
What technologies are we going to use?
- NodeJS: a tool to server-side execute JavaScript code.
- Express: a micro-framework to make server development faster.
- Mongoose: a library that helps us connect to our MongoDB instance.
- JWT (JSON Web Token): an encrypted string that gets generated by the server and is stored by the client. On every request, that string will be sent by the client and will be verified by the server.
- Bcrypt: a library we will use to hash our passwords.
- BodyParser: will help us to retrieve body parameters when handling a request.
Setup our environment
First of all, be sure to have NodeJS installed. If you haven’t, check out this link. Then, create a new MongoDB instance. You can create one here, for free.
Finally, install NPM packages in our project folder via command line.
npm install express jsonwebtoken body-parser bcryptjs
Ready to code!
Now, we need to create our server scripts:
- app.js, in which we’ll handle all our server requests.
- db.js, which will contain our Database models.
Let’s create a very simple Express application: it will be the basic structure of our app.
The “SECRET_JWT_CODE” is the encryption key we are going to use when generating our tokens.
Before proceeding implementing our endpoints, we should get a look at the db.js file.
db.js
This file essentially creates our DB model schemas. This means that each user related data is going to be saved under a document (collection) called “users” and will have two attributes, “email” and “password”. Of course, you can create as many models as you want, with as many attributes as you want.
Now we need to implement our routing system. The app will essentially have two endpoints, the first one for the sign up and the second one for the login.
app.js — sign upapp.js — login
It works!
Screenshot of the data saved on our DB after having made a call to our /user/signup endpoint
Final steps
We successfully implemented our authentication system. Now, the client should save the token after the login and send it back every time it makes a new request.
Remember that Json Web Tokens have an expiration time. There are many ways to stay the user logged in. For example, whenever it happens, the client could refresh the token making a new login call.
On the backend side, this is how you could check if the token is valid:
app.jsapp.js
You can find the Github gist here!😊