Let's start with a simple example of a college management system.
- 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:
- Simple and fast
Disadvantage:
- 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:
- Easy and only one middleware, no need to add the same code in every route.
Disadvantage:
- Hard-coded authorized roles in middleware's parameter ex.['Teacher','Admin']
Top comments (0)