Nodejs JWT Authentication – Nodejs/Express RestAPIs + JSON Web Token + BCryptjs + Sequelize + MySQL

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-feature-image-new

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).

Related posts:
Sequelize Many-to-Many association – NodeJS/Express, MySQL
Sequelize ORM – Build CRUD RestAPIs with NodeJs/Express, Sequelize, MySQL
– Full stack with Angular: Angular & Nodejs JWT Authentication fullstack

Technologies

– Nodejs/Express
– Json Web Token
– BCryptjs
– Sequelize
– MySQL

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-sequelize-decoded-token

See more at: Introduction to JSON Web Tokens

Overview

Demo

Project Structure

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

  • config package defines MySQL Database Configuration, JWT Secret Key & User Roles.
  • model package defines Role & User Sequelize models.

    nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-many-to-many-user-role

  • 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-sequelize-sign-up

Sign In ->

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-adam-sign-in

Access API Successfully ->

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-adam-access-user-role-api

Unauthorized Access ->

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-adam-can-NOT-access-PM-role-api

Practice

Create Nodejs Project

Following the guide to create a NodeJS/Express project

Install Express, Sequelize, MySQL, Json Web Token, Bcryptjs:

-> package.json file:

Create Sequelize Models

User model ->

Role model:

Sequelize Database Configuration

/app/config/env.js file ->

/app/config/db.config.js ->

Because Role & User has many-to-many association, so we use belongsToMany to configure them.

-> See more at: Sequelize Many-to-Many association – NodeJS/Express, MySQL

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

– Create /app/config/config.js file that defines jwt-secret-key & User Roles.

Server

/app/server.js file ->

Run & Check Results
Start Nodejs Server

– Run Nodejs server by cmd npm start -> Logs:

-> Check MySQL database:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-table-schema

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-roles-tables

Sign Up

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-sign-up

-> All Logs of Sign Up:

-> MySQL records:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-after-signup-data

SignIn and Access Protected Resources

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

-> Sign In:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-adam-sign-in

-> Access Protected Resources:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-adam-access-user-role-api

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-adam-can-NOT-access-PM-role-api

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-sequelize-jack-sign-in

-> Access Protected Resources:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-JACK-can-access-user-role-api

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-JACK-can-access-PM-role-api

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-JACK-can-NOT-access-ADMIN-role-api

Thomas can access all URLs.

-> Sign In:

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

-> Access Protected Resource:

nodejs-jwt-authentication-express-bcryptjs-jsonwebtoken-sequelize-THOMAS-can-access-ADMIN-role-api

SourceCode

Nodejs-JWT-Authentication

By grokonez | October 1, 2018.

Last updated on March 20, 2019.



Related Posts


12 thoughts on “Nodejs JWT Authentication – Nodejs/Express RestAPIs + JSON Web Token + BCryptjs + Sequelize + MySQL”

  1. Hello, i am getting an error on getRoles(), Unhandled rejection TypeError: Cannot read property ‘getRoles’ of null, if you can help me it will be great ! Really great tutorial on authentication.

    1. Hi friend, I has the same problem, I tried to fix It and I got It, the problem is because in the relationship (User Role) you should call with include Rol model in FindByPK (FindByID) with this your problem is fixed. this is the complete function:

      I hope that is not late to fix .

      King regards.

      Judlup

  2. Great Tutorial!
    Does this support database migration?
    If so, how can I add/edit/remove a field in a table without losing records?

    Thanks

  3. Hi,
    Many thanks for this tutorial, it helps me a lot for my project.
    It’s really well explained and illustrated !

    Thanks

  4. How about logout and update of password/change of password by user?

    You have done a good job, kindly finish the help for us.

  5. Hello, is there anyone can modify the same code which will be having only two roles say Admin and Volunteer and can access these as same as in the above code.

Got Something To Say:

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

*