1.1.2 • Published 7 months ago

rbac-express v1.1.2

Weekly downloads
-
License
ISC
Repository
-
Last release
7 months ago

rbac-express

A simple and lightweight middleware for implementing Role-Based Access Control (RBAC) in Express.js applications using JWT.


Features

  • 🚀 Easy-to-use middleware for protecting Express.js(tested on express only) routes.
  • 🔒 Built-in support for JWT-based authentication.
  • Role-based access control with minimal configuration.
  • 🔗 Highly flexible and customizable.

Installation

Install the library using npm:

npm install rbac-express

on your main app should install Express.JS & and jsonwebtoken for create jwt.


Usage

  1. Setup JWT Authentication and Middleware : Add the middleware to your Express.js app to protect routes based on user roles.
const express = require("express");
const jwt = require("jsonwebtoken");
const { authorize } = require("rbac-express");

const app = express();

// JWT secret key
const SECRET_KEY = "your-secret-key";

//Simulate user login and generate JWT
app.post("/login", (req, res) => {
  const user = { id: 1, username: "user1", roles: ["admin"] }; // Replace with your user data
  const token = jwt.sign(user, SECRET_KEY, { expiresIn: "1h" });
  res.json({ token });
});

// Protected route
app.get(
  "/admin",
  authorize({
    secret: SECRET_KEY, // Your JWT secret key
    roles: ["admin"], // Roles allowed to access this route
  }),
  (req, res) => {
    res.send("Welcome, Admin!");
  }
);

// Start the server
app.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});

API Documentation

Middleware Options

  1. secret : required, string (The secret key used to verify JWTs.)
  2. roles : required, array of strings (The array of roles allowed to access the route.)

JWT Payload Requirements

The JWT payload must contain a roles field, which is an array of roles assigned to the user. And you can add any other fields to the token as you wish.

{
  "id": 1,
  "username": "user1",
  "roles": ["admin", "editor"]
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT


Contact me on 😎

H. Kavinda Dissanayake

Email : kavindapvt@gmail.com

Linkdin : www.linkedin.com/in/dissanayake-kavinda

GitHub : https://github.com/kavinda-KPD

1.1.2

7 months ago

1.1.0

7 months ago

1.0.0

7 months ago