Back to projects
Role-Based Authorization API

Role-Based Authorization API

Madhuka Malshan / March 13, 2025

Introduction

This is a role-based authorization API built with Node.js, Express.js, and MongoDB. The API supports user authentication, registration, and access control based on user roles. It features secure password handling and JSON Web Token (JWT) authentication.

Features

  • User Authentication with JWT: Secure authentication using JSON Web Tokens.
  • Role-Based Access Control: Protected routes accessible based on user roles.
  • Password Hashing with bcrypt: Secure password storage using bcrypt.js.
  • Modular Code Structure: Organized and maintainable codebase.

Technologies Used

  • Backend: Node.js, Express.js
  • Database: MongoDB (using Mongoose ODM)
  • Authentication: JSON Web Tokens (JWT)
  • Password Security: bcrypt.js
  • Environment Variables: dotenv

Project Structure

The project consists of the following main parts:

  • Backend: Node.js and Express.js for handling API requests.
  • Database: MongoDB for storing user data and roles.
  • Config Files: Includes environment settings and database configurations.

Installation

Clone the Repository

Clone the repository using:

    git clone https://github.com/madhuka2002/RoleBasedAuthorization_API.git
    cd RoleBasedAuthorization_API

Install Dependencies

Install all required dependencies:

    npm install

Configure Environment Variables

Create a .env file with the following content:

CONNECTION_STRING=<your-mongodb-connection-string>
JWT_SECRET=<your-jwt-secret>
PORT=7001

Start the Server

Start the development server:

    npm start

Usage

Authentication Endpoints

- **Register**: `POST /api/auth/register`
{
  "username": "user1",
  "password": "user123",
  "role": "user"
}
- **Login**: `POST /api/auth/login`
    {
    "username": "user1",
    "password": "user123"
    }

API Endpoints

Auth Routes

| Route | Method | Description | |-------|--------|-------------| | /api/auth/register | POST | Register a new user | | /api/auth/login | POST | Login and get JWT token |

Protected Routes

| Route | Method | Description | |-------|--------|-------------| | /api/users/ | GET | Get all users (Admin only) | | /api/users/:id | GET | Get a specific user | | /api/users/:id | PUT | Update user details | | /api/users/:id | DELETE | Delete a user |

Error Handling

The API provides consistent error messages:

  • 401 Unauthorized: Missing or invalid authentication token.
  • 403 Forbidden: Access denied for the requested resource.
  • 404 Not Found: Resource does not exist.
  • 500 Internal Server Error: General server issues.

Contributing

Contributions are welcome! Please fork this repository and submit pull requests for new features, bug fixes, or improvements.