loading...

Role-based access to API in Node.js

shadabshaikh0 profile image Shadab Majid Shaikh Updated on ・1 min read

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']

Posted on by:

shadabshaikh0 profile

Shadab Majid Shaikh

@shadabshaikh0

SUMMARY - Team-oriented, Creative software professional with strong interpersonal skills. - Winner of Smart India Hackathon 2018 & 2019. - Fullstack Developer - Actively participates in Hackathons

Discussion

markdown guide