Node.js Techniques — Role Based Authorization at the API level
APIs are everywhere and have many different faces and capabilities.
Essentially APIs act as transports vehicles 🚗 that pull information from one source and feed it to another. For example, Google maps API used in navigation systems or Stripe API used for Online payments, etc.
APIs in a lot of applications serve as data points for client-based applications 🖥️ or other API clients, with read-write permissions; and as such certain endpoints need to be protected to provide access to privileged users of the application.
In this tutorial, we’ll go through a simple implementation of role-based authorization or access control in a Node.js API with the Express framework. In this example, I’ll work with JWT, for token-based authentication in Node.js.
This directory contains helper functions written as independent and reusable bits of code invoked within a
controller file when needed.
JWTSECRET property in the
.env is used by the API to sign and verify the JWT token. do update it with your unique random string to restrict unauthorized access to your application.
Implement the authhelper function as a Nodejs Middleware in the API routes
This middle-ware is written to intercept a request for a route. the middleware here, checks if the bearer token is sent as header or body information if the token is still valid and if so, sends the token payload such as
user_id and role to another method within the request life cycle.
The middle-ware as used in this snippet is called
The above routes are protected with a middleware that checks for a bearer token and extracts the payload, coupled with an error handler.
If there are no errors in the payload extracted from the token, we send this payload containing user data to the controller.
Access the Nodejs route Controller
This controller defines all routes for the API, the route definitions are grouped together at the top of the file and the route implementations are below.
Routes that use the
mustBeLoggedIn middleware are restricted to authenticated users, if the role is included (e.g. authorize(Role.Admin or Role.Superuser)) then the route is restricted to users in the specified role/roles.
Otherwise, if the role is not included (e.g.
mustBeLoggedIn()) then the route is restricted to all authenticated users regardless of their role. Thus Routes that don't use the authorize middleware are publicly accessible.
This is a simple implementation of a role-based Authorization or access control on an API.
I want to learn about the awesome projects you build with larger-scale implementations of access control for application APIs 😃.
Originally published at https://blog.nextwebb.tech.