Node.js JWT Authentication & MongoDB – Express RestAPIs + JSON Web Token + BCryptjs + Mongoose

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-feature-image

JSON Web Token defines a compact and self-contained way for securely transmitting information as a JSON object.
In the tutorial, we show how to build a Nodejs Token Authentication RestAPIs with JSON Web Token (JWT) and MongoDB.

Related posts:
Mongoose Many-to-Many related models with NodeJS/Express, MongoDB
Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose

Technologies

– Nodejs/Express
– Json Web Token
– BCryptjs
– Mongoose
– MongoDB

JSON Web Token

JSON Web Token (JWT) defines a compact and self-contained way for securely transmitting information between parties as a JSON object.

-> Scenarios where JSON Web Tokens are useful:

  • Authorization: the most common scenario for using JWT. Single Sign On is a feature that widely uses JWT
  • Information Exchange: Because JWTs can be signed, JSON Web Tokens are a good way of securely transmitting information between parties.

JSON Web Tokens consist of 3 parts:

  • Header
  • Payload
  • Signature

-> JWT looks like Header-Base64-String.Payload-Base64-String.Signature-Base64-String

Header consists of two parts:

  • token type.
  • hashing algorithm.

-> Example:

Payload contains the claims. Claims are statements about an entity and additional information.
There are 3 types of claims ->

  • Registered claims -> These are a set of predefined claims: iss (issuer), exp (expiration time), sub (subject)
  • Public claims
  • Private claims

Example ->

Signature -> To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

Example ->

Combine all together, we get 3 Base64-URL strings separated by dots,

Example:

– Encoded ->

– Decoded ->

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-decoded-token

See more at: Introduction to JSON Web Tokens

Overview

Project Structure

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-project-structure

  • config package defines MongoDB Database Configuration, JWT Secret Key & User Roles.
  • model package defines Role & User Mongoose models.
  • router package defines RestAPI URLs, verification functions for signup, & verification JWT token function for signin.
  • controller package defines proccesing functions for each RestAPIs declared in router package.
Workflow

We will define 5 workflows as below ->

  • SignUp Scenarios:

    – Code in router.js ->

  • SignIn Scenarios:

    – Code in router.js ->

  • Access User Content:

    – Code in router.js ->

  • Access PM Content:

    – Code in router.js ->

  • Access Admin Content

    – Code in router.js ->

Goal

Sign Up ->

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-ADAM-sign-up

Sign In ->

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-ADAM-Sign-In

Access API Successfully ->

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-ADAM-access-User-API-successfully

Unauthorized Access ->

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-ADAM-can-NOT-access-PM-apis

Practice

Create Nodejs Project

Following the guide to create a NodeJS/Express project

Install Express, Mongoose, Json Web Token, Bcryptjs:

-> package.json file:

Create Mongoose Models

User model ->

Role model:

Project Configuration

/app/config/config.js file ->

Define RestAPIs Router

We define 5 RestAPIs in /app/router/router.js

We need implement middleware functions to do a verification for SignUp & SignIn:

/app/router/verifySignUp.js implements 2 middleware functions:

  • checkDuplicateUserNameOrEmail -> checking the posted username or email is duplicated or NOT
  • checkRolesExisted -> checking the posted User Role is existed or NOT

/app/router/verifyJwtToken.js implements 3 middleware functions:

  • verifyToken -> checking a JWT token is valid or NOT
  • isAdmin -> checking an User has ADMIN role or NOT
  • isPmOrAdmin -> checking an User has PM or ADMIN role or NOT

Implement Controller

/app/controller/controller.js exports 5 funtions:

  • signup -> be used to register new User
  • signin -> be used to Login
  • userContent -> get User Info
  • managementBoard -> get Management Board Content
  • adminBoard -> get Admin Board Content

Server

/app/server.js file ->

Run & Check Results
Start Nodejs Server

– Run Nodejs server by cmd npm start.

-> Check MongoDB database:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-database-after-initial

Sign Up

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-ADAM-sign-up

-> MongoDB records:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-database-after-sign-up-all-user-records

SignIn and Access Protected Resources

Adam can access api/test/user url, can NOT access others.

-> Sign In:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-ADAM-Sign-In

-> Access Protected Resources:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-ADAM-access-User-API-successfully

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-ADAM-can-NOT-access-PM-apis

Jack can access api/test/user & api/test/pm url.
Can NOT access /api/test/admin url.

-> Sign In:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-JACK-sign-in

-> Access Protected Resources:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-JACK-access-User-API-successfully

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-JACK-access-PM-API-successfully

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-JACK-can-NOT-access-ADMIN-API

Thomas can access all URLs.

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-THOMAS-sign-in

-> Access Protected Resource:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-mongoose-THOMAS-access-ADMIN-API-successfully

SourceCode

Node.js-JWT-Auth-Mongoose

By grokonez | October 6, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*