DEV Community

Shadab Majid Shaikh
Shadab Majid Shaikh

Posted on • Updated on

Role-based access to API in Node.js

Let's start with a simple example of a college management system.

  1. Can students modify their marks? => NO, students are not authorized only teachers can do this :(

But how this is handled in the college management system, the answer is

Role-based authorization to API

How to authorize resources according to the user role, What is your approach?

1. Simple and easy approach

Let's declare authorized roles in every endpoint and check with the user role if the user's role is present in authorized roles. Hurray! You have access.
Ex:

route.get('/changemarks',(req, res) => {
    const authorizedRoles = ['teacher','admin']
    // Extract user role from req && Let's assume userRole is student
    const userRole = extractUserRole(req)
    // student is not present in authorizedRoles array 
    const isAuthorized = authorizedRoles.includes(userRole);
    if(!isAuthorized){
       // return with your customized error
    }
})

Advantage:

  1. Simple and fast

Disadvantage:

  1. Not easily configurable

2. Middleware in every route of your project.

Don't you think the above code should be separated out as an authorization handler? Let's add authorization handler in every request as middleware.

route.get('/changemarks', authorizationHandler(['Teacher','Admin'], (req, res) => {
})

const authorizationHandler =  (authorizedRoles) => {
  return function(req, res, next) {
    const userRole = extractUserRole(req)
    if ( !authorizedRoles.includes(userRole) ) res.redirect(...);
    else next();
  }   
})

Advantage:

  1. Easy and only one middleware, no need to add the same code in every route.

Disadvantage:

  1. Hard-coded authorized roles in middleware's parameter ex.['Teacher','Admin']

Top comments (0)