Node.js Express Login example with MongoDB
Tags: node, javascript, security, webdev
Published: 2020-12-26 09:45:57

In this tutorial, we're gonna build a Node.js & MongoDB example that supports User Authentication (Login, Registation) & Authorization with [JSONWebToken](https://www.npmjs.com/package/jsonwebtoken) (JWT). You'll know:

*   Appropriate Flow for User Signup & User Login with JWT Authentication
*   Node.js Express Architecture with CORS, Authenticaton & Authorization middlewares, Mongoose ODM
*   Way to configure Express routes to work with JWT
*   How to define Mongoose Models for Authentication and Authorization
*   How to use Mongoose to interact with MongoDB Database

Full Article: [https://bezkoder.com/node-js-mongodb-auth-jwt/](https://bezkoder.com/node-js-mongodb-auth-jwt/)

Update: [using HttpOnly cookies](https://www.bezkoder.com/node-js-express-login-mongodb/)

## Token Based Authentication
Comparing with Session-based Authentication that need to store Session on Cookie, the big advantage of Token-based Authentication is that we store the JSON Web Token (JWT) on Client side: Local Storage for Browser, Keychain for IOS and SharedPreferences for Android… So we don’t need to build another backend project that supports Native Apps or an additional Authentication module for Native App users.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/osy8rwtr9y37vhmlp2za.png)

There are three important parts of a JWT: Header, Payload, Signature. Together they are combined to a standard structure: `header.payload.signature`.

The Client typically attaches JWT in **Authorization** header with Bearer prefix:
```
Authorization: Bearer [header].[payload].[signature]
```
Or only in **x-access-token** header:
```
x-access-token: [header].[payload].[signature]
```
For more details, you can visit:
[In-depth Introduction to JWT-JSON Web Token](https://bezkoder.com/jwt-json-web-token/)

## Node.js Login & Registration with MongoDB example
We will build a Node.js Express application in that:

- User can signup new account, or login with username & password.
- By User's role (admin, moderator, user), we authorize the User to access resources

These are APIs that we need to provide:

- POST 	`/api/auth/signup` 	signup new account
- POST 	`/api/auth/signin` 	login an account
- GET 	`/api/test/all` 	retrieve public content
- GET 	`/api/test/user` 	access User's content
- GET 	`/api/test/mod` 	access Moderator's content
- GET 	`/api/test/admin` 	access Admin's content

## Flow for Signup & Login with JWT Authentication
The diagram shows flow of User Registration, User Login and Authorization process.

![node-js-express-login-mongodb-example-flow](https://dev-to-uploads.s3.amazonaws.com/i/crv22c186lcj9spryp44.png)

A legal JWT must be added to HTTP **x-access-token** Header if Client accesses protected resources.

You may need to implement Refresh Token like this:

![node-js-express-refresh-token-example-flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wohb3x8su8khbx4mppk5.png)

More details at: [Node.js and MongoDB: JWT Refresh Token example](https://bezkoder.com/jwt-refresh-token-node-js-mongodb/)

Update: [using HttpOnly cookies](https://www.bezkoder.com/node-js-express-login-mongodb/)

## Node.js Login & Registration system with MongoDB Architecture

You can have an overview of our Node.js Express App with the diagram below:

![node-js-express-login-mongodb-example-](https://dev-to-uploads.s3.amazonaws.com/i/y9dvkos1sv3neaku3i18.png)

Via _Express_ routes, **HTTP request** that matches a route will be checked by **CORS Middleware** before coming to **Security** layer. **Security** layer includes:

*   JWT Authentication Middleware: verify SignUp, verify token
*   Authorization Middleware: check User's roles with record in database

An error message will be sent as HTTP response to Client when the middlewares throw any error, . **Controllers** interact with MongoDB Database via _Mongoose_ library and send **HTTP response** (token, user information, data based on roles...) to Client.

For more details, implementation and Github, please visit:
[https://bezkoder.com/node-js-mongodb-auth-jwt/](https://bezkoder.com/node-js-mongodb-auth-jwt/)

## Further Reading
Related Posts:
- [MERN stack Authentication example](https://bezkoder.com/react-node-mongodb-auth/)
- [MEAN stack Authentication with Angular 8 example](https://bezkoder.com/mean-stack-authentication-angular-8/)
- [MEAN stack Authentication with Angular 10 example](https://bezkoder.com/mean-stack-authentication-angular-10/)
- [Node.js, Express & MongoDb: Build a CRUD Rest Api example](https://bezkoder.com/node-express-mongodb-crud-rest-api/)
- [MongoDB One-to-Many Relationship tutorial with Mongoose examples](https://bezkoder.com/mongoose-one-to-many-relationship/)
- [MongoDB Many-to-Many Relationship with Mongoose examples](https://bezkoder.com/mongodb-many-to-many-mongoose/)

You may need to implement Refresh Token like this:

![node-js-express-refresh-token-example-flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wohb3x8su8khbx4mppk5.png)

More details at: [Node.js and MongoDB: JWT Refresh Token example](https://bezkoder.com/jwt-refresh-token-node-js-mongodb/)

Front-end that works well with this:
- [Angular 8](https://bezkoder.com/angular-jwt-authentication/)
- [Angular 10](https://bezkoder.com/angular-10-jwt-auth/)
- [Angular 11](https://bezkoder.com/angular-11-jwt-auth/)
- [Angular 12](https://bezkoder.com/angular-12-jwt-auth/)
- [Vue.js](https://bezkoder.com/jwt-vue-vuex-authentication/)
- [React (without Redux)](https://bezkoder.com/react-jwt-auth/)
- [React Redux](https://bezkoder.com/react-redux-jwt-auth/)

Dockerize:
[Docker Compose: Node.js Express and MongoDB example](https://www.bezkoder.com/docker-compose-nodejs-mongodb/)