Production-ready authentication microservice β Node.js, Express, MongoDB, and JWT. User registration, login, token refresh, and role-based access control.
- 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 control β
userandadminroles with middleware guards - Protected routes β auth and role middleware applied per route
- Clean architecture β controllers / middleware / models / routes separated
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
- Node.js 18+
- MongoDB (local or Atlas)
git clone https://github.com/DIYA73/api-auth-service.git
cd api-auth-service
cp .env.example .envPORT=3000
MONGODB_URI=mongodb://localhost:27017/auth-service
JWT_SECRET=your-access-token-secret
JWT_REFRESH_SECRET=your-refresh-token-secret
JWT_EXPIRES_IN=15m
JWT_REFRESH_EXPIRES_IN=7dnpm install
npm run dev # development (nodemon)
npm start # productionPOST /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 }
GET /user/profile # requires valid JWT
GET /admin/dashboard # requires admin role
# 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"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.
MIT