Skip to content

Implement role based access control, JWT, Express.js , Node.js

Last updated on November 21, 2022

In this post, We gonna build an access control layer using express-jwt-permissions. ACL will keep users from accessing information not meant for them.

We gonna create the express.js application for a role-based access control example.

let’s create a folder called aclJWTExpress

$ mkdir aclJWTExpress

After creating, change the directory to aclJWTExpress

$ cd aclJWTExpress

Now initialize the project with the npm init command

$ npm init --yes

--yes tells npm to use the default options while generating the package.json so you are not asked any questions

After running the command above, you should have a package.json file in the aclJWTExpress directory.

Below are the npm modules that we are going to use in this tutorial
express – The popular Node framework
express-jwt-permissions – Permissions middleware for JWT tokens
body-parser – Will let us get parameters from our POST requests
jsonwebtoken – JSON Web Token sign and verification
sequelize – Sequelize is a promise-based ORM for Node.js v4 and up
sequelize-cli – sequelize-cli is usful to generate model, migration file..etc
mysql2 – MySQL client for Node.js with focus on performance

Install all the dependencies with the below command

npm install --save express body-parser sequelize-cli sequelize mysql2 jsonwebtoken express-jwt-permissions jsonwebtoken

Initializes sequelize

Now create an empty project with sequelize cli init command. It will generate migrations, seeders, config and models directories, and defulat config file.

$ node_modules/.bin/sequelize init

I got the following log in my console:

Created "config\config.json"
Successfully created models folder at "C:\Users\arjun\aclJWTExpress\models".
Successfully created migrations folder at "C:\Users\arjun\aclJWTExpress\migrations".
Successfully created seeders folder at "C:\Users\arjun\aclJWTExpress\seeders".

If you are using windows OS, open models/index.js file and correct the config file path.
Change the var config = require(__dirname + '/..\config\config.json')[env]; to var config = require(__dirname + '/../config/config.json')[env];

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments