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=3000MONGODB_URI=mongodb://localhost:27017/auth-serviceJWT_SECRET=your-access-token-secretJWT_REFRESH_SECRET=your-refresh-token-secretJWT_EXPIRES_IN=15mJWT_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