Learn How To Implement Role-based API Authorization In Node.js

In this blog, we will explain the implementation of Role-based API authorization in node.js. We will use an Express framework at the backend to implement a Role-based secure REST API. The flow of the Node Express REST API is very simple. Every REST API endpoint is restricted by Authentication and Authorization. Authentication finds the matching username and password from the User model, and Authorization sees the matching Role with permissions to the specific REST API endpoint. So, the relation of the User, Role, and Permission model will be:

  1. User has one or many Roles
  2. Each secure endpoint has a Role based access control

So we can restrict some endpoints for specific user Roles and handle the multiple users in the application along with the reliability of endpoints and resources.

Folder Structure for Node.js Role Based API Authorization Middleware

First, we must maintain a proper folder structure for Controllers, Services, Models, Repository and Middlewares for the node js project.

Writing enums for user roles and model

We can consider that we have two types of users in the application User and Admin. So there will be two Roles we have to declare with enums. Basic implementation of enums, we can define an object to encapsulate the enum type and assign a key for each enum value.

import { model, Schema } from 'mongoose';

import lodash from 'lodash';

export enum Roles {

 USER = "USER",

 ADMIN = "ADMIN",

}

const userSchema: Schema = new Schema(

 {

   firstName: { type: String, required: false },

   lastName: { type: String, required: false },

   email: { type: String, required: false },

   avatar: { type: String, required: false },

   provider:{ type: String, required: false },

   providerId:{ type: String, required: false },

   roles:{

       type:[String],

       enum:Object.keys(Roles),

       default:Roles.USER

   }

 },


 {

   collection: 'users',

   timestamps: true

 },

);

const User = model('User', userSchema);

export default User;

Writing controller for user API access endpoint

As the client hits the API endpoint and gets routed to the controller of our express application, we need to add a middleware of user & user Role authorization. In the below snippet, you can see the code and how to pass arguments to your authorization middleware.

import express from "express";

import { Roles } from "../DB/Schemas/User";

const router = express.Router();

import userService  from './user.service';

import authorize from "./middlewares/authorize"

// routes

router.post('/authenticate', authenticate);     // public route

router.get('/users', authorize([Roles.ADMIN]), getAll); // admin only can see all users

router.get('/users/:id', authorize(), getById);       // all authenticated users pass empty or pass [Roles.USER,Roles.ADMIN]

module.exports = router;

function authenticate(req, res, next) {

   userService.authenticate(req.body)

       .then(user => user ? res.json(user) : res.status(400).json({ message: 'Username or password is incorrect' }))

       .catch(err => next(err));

}

function getAll(req, res, next) {

   userService.getAll()

       .then(users => res.json(users))

       .catch(err => next(err));

}

function getById(req, res, next) {

   const currentUser = req.user;

   const id = parseInt(req.params.id);

   userService.getById(id)

       .then(user => user ? res.json(user) : res.sendStatus(404))

       .catch(err => next(err));

Writing authorize role middleware

This is an important section that is the center point of this blog. This authorizes the Role middleware function to accept the argument, i.e., The array of Roles we passed from the controller route to this authorized middleware function.

We mainly extract that array in this middleware function and decode the JWT token passed from the front end into the authorization headers. Once we decode the JWT token, we find that particular user object and Role.

We use the express-jwt module, which automatically takes the token from the authorization header and verifies it, and attaches the user object to our request object.

jwt({ secret, algorithms: ['HS256'] })

After this line of code, we use the callback function in which we get the request object with the associated req.user object in it if the token is valid. In our user model, we have already defined the user’s Roles, an array of Roles associated with that user account.

So as an output from above function we get request object as follows

Request = { 

   body:{...},

   user: {

             …rest,

             roles:[ “ADMIN”]

             }

  }
import jwt from "express-jwt"

export const authorize(roles = []) {

   // roles param can be a single role string (e.g. Role.User or 'User')

   // or an array of roles (e.g. [Role.Admin, Role.User] or ['Admin', 'User'])

   if (typeof roles === 'string') {

       roles = [roles];

   }


   return [

       // authenticate JWT token and attach user to request object (req.user)

       jwt({ secret:process.env.secret, algorithms: ['HS256'] }),




       // authorize based on user role

       (req, res, next) => {

           if (roles.length && !roles.includes(req.user.role)) {

               // user's role is not authorized

               return res.status(401).json({ message: 'Unauthorized' });

           }




           // authentication and authorization successful

           next();

       }

   ];

}

Next, we try to match the Role of the user we get from req.user object and the Role we get from the function argument to match. If Roles are matched, we call the nextFunction, so it executes the next function in the API route stack without any trouble. If Roles don’t get matched, then we thow a status 401 Unauthorized error saying that “This resource is not available for the current user.”

In this way, we can protect out routes in case to manage the multiple user Roles in the application along with API endpoint access control for different user Roles.

Advantages Of Node.js Role Based API Authorization

  • We can easily differentiate the API endpoints for each user type.
  • We can protect API endpoints and make the data available only for the user of a particular Role who has permission to access that resource.
  • We can reuse the same endpoints for multiple users and restrict them.
coma

Conclusion

In this article, we learned about Implementing Role-based API authorization in Node.js using Express, Express-jwt and authentication middlewares. Furthermore, we learned how we could restrict API endpoints in Express applications based on user Roles and secure the APIs.

Abhishek

Abhishek is a Full-stack developer with 2+ years of experience. He has experience in web technologies like  ReactJS, NodeJs, MongoDB, Java(Spring boot). His expertise is building MERN stack web applications, building full stack web application in MERN stack with well-designed, testable and efficient and optimized code. He loves to learn new technologies.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks
coma

Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.

author
George Hodulik
CEO, Stealth Startup, Ex-Google