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.

Keep Reading

Keep Reading

Launch Faster with Low Cost: Master GTM with Pre-built Solutions in Our Webinar!

Register Today!
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?