Skip to content

Repository files navigation

🔐 API Authentication Service

Production-ready authentication microservice — Node.js, Express, MongoDB, and JWT. User registration, login, token refresh, and role-based access control.

Node.jsExpressMongoDBJWTLicense: MIT


Features

  • User registration and login — email + password, hashed with bcryptjs
  • JWT access tokens — short-lived, sent in Authorization header
  • Refresh tokens — rotate tokens without requiring re-login
  • Role-based access controluser and admin roles with middleware guards
  • Protected routes — auth and role middleware applied per route
  • Clean architecture — controllers / middleware / models / routes separated

Project structure

api-auth-service/src/
├── config/
│ └── db.js # MongoDB connection
├── controllers/
│ └── auth.controller.js # Register, login, refresh logic
├── middleware/
│ ├── auth.middleware.js # JWT verification
│ └── role.middleware.js # Role-based guard
├── models/
│ └── User.js # Mongoose user schema
├── routes/
│ ├── auth.routes.js # /auth/*
│ ├── protected.routes.js # /user/* (auth required)
│ └── admin.routes.js # /admin/* (admin role required)
└── server.js

Quick start

Prerequisites

  • Node.js 18+
  • MongoDB (local or Atlas)

1. Clone and configure

git clone https://github.com/DIYA73/api-auth-service.git
cd api-auth-service
cp .env.example .env
PORT=3000MONGODB_URI=mongodb://localhost:27017/auth-serviceJWT_SECRET=your-access-token-secretJWT_REFRESH_SECRET=your-refresh-token-secretJWT_EXPIRES_IN=15mJWT_REFRESH_EXPIRES_IN=7d

2. Install and run

npm install
npm run dev # development (nodemon)
npm start # production

API reference

Auth routes

POST /auth/register
Body: { "email": "user@example.com", "password": "secret", "role": "user" }
POST /auth/login
Body: { "email": "user@example.com", "password": "secret" }
Returns: { access_token, refresh_token }
POST /auth/refresh
Body: { "refresh_token": "..." }
Returns: { access_token }

Protected routes

GET /user/profile # requires valid JWT
GET /admin/dashboard # requires admin role

Example

# Register
curl -X POST http://localhost:3000/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"you@example.com","password":"secret123"}'# Login
TOKEN=$(curl -s -X POST http://localhost:3000/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"you@example.com","password":"secret123"}'| jq -r .access_token)# Access protected route
curl http://localhost:3000/user/profile \
-H "Authorization: Bearer $TOKEN"

Notes

This service was built as a standalone authentication microservice. It is intended to be deployed independently and consumed by other services via HTTP or an API gateway.

License

MIT

About

🔐 Production-ready authentication microservice with Node.js, Express, MongoDB, JWT. User registration, login, token refresh, role-based access

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages