Production-ready authentication microservice built with Node.js, Express, MongoDB, and JWT. Provides secure user registration, login, and token-based authentication for modern web applications.
A standalone authentication microservice designed to handle user management and authentication for any frontend application. Built with security best practices, it provides a robust foundation for implementing authentication in React, Vue, Angular, or vanilla JavaScript applications.
- 🔐 Secure Authentication: JWT-based stateless authentication
- 👤 User Management: Registration, login, profile management
- 🔒 Password Security: bcrypt hashing with salt rounds
- 🛡️ Protected Routes: Middleware for route protection
- 👥 Role-Based Access: Admin, User role support
- 🔄 Token Refresh: Automatic token renewal
- 📧 Email Verification: Optional email confirmation (planned)
- 🔑 Password Reset: Secure password recovery flow (planned)
- ⚡ High Performance: Optimized for speed and scalability
- 📊 MongoDB Integration: Efficient data storage with Mongoose
🚀 Node.js 18+ (JavaScript Runtime)
🌐 Express.js 4+ (Web Framework)
🗄️ MongoDB 6+ (Database)
🔗 Mongoose (ODM)
🔐 jsonwebtoken (JWT Auth)
🛡️ bcrypt (Password Hashing)
🔒 helmet (Security Headers)
✅ express-validator (Input Validation)
🌍 cors (Cross-Origin Resource Sharing)
📦 dotenv (Environment Variables)
🔄 nodemon (Auto-restart)
🧪 Jest (Testing - optional)
┌──────────────────────────────────────┐
│ Frontend Applications │
│ (React / Vue / Angular / Vanilla) │
└──────────────┬───────────────────────┘
│
▼
┌──────────────────────────────────────┐
│ API Authentication Service │
├──────────────────────────────────────┤
│ │
│ ┌────────────┐ ┌──────────────┐ │
│ │ Register │ │ Login │ │
│ └────────────┘ └──────────────┘ │
│ │
│ ┌────────────┐ ┌──────────────┐ │
│ │ Token │ │ Refresh │ │
│ │ Verify │ │ Token │ │
│ └────────────┘ └──────────────┘ │
│ │
│ ┌────────────┐ ┌──────────────┐ │
│ │ Profile │ │ Logout │ │
│ └────────────┘ └──────────────┘ │
│ │
└──────────────┬───────────────────────┘
│
▼
┌──────────────────────────────────────┐
│ MongoDB Database │
│ (Users Collection) │
└──────────────────────────────────────┘
Endpoint: POST /api/auth/register
Features:
- Email uniqueness validation
- Password strength requirements
- Automatic password hashing (bcrypt)
- User role assignment
- Creation timestamp
Request:
{
"name": "John Doe",
"email": "john@example.com",
"password": "SecurePass123!"
}Response:
{
"success": true,
"message": "User registered successfully",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "123abc",
"name": "John Doe",
"email": "john@example.com",
"role": "user"
}
}Endpoint: POST /api/auth/login
Features:
- Email/password verification
- Password comparison (bcrypt)
- JWT token generation
- Refresh token issuance (optional)
Request:
{
"email": "john@example.com",
"password": "SecurePass123!"
}Response:
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "...",
"expiresIn": "7d"
}Endpoint: GET /api/users/profile
Features:
- JWT verification middleware
- Token expiration check
- User data retrieval
- Role-based access control
Headers:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Response:
{
"success": true,
"user": {
"id": "123abc",
"name": "John Doe",
"email": "john@example.com",
"role": "user",
"createdAt": "2024-01-15T10:00:00Z"
}
}Endpoint: POST /api/auth/refresh
Features:
- Refresh token validation
- New access token generation
- Extended session management
- Node.js 18+
- MongoDB 6+ (local or MongoDB Atlas)
- npm or yarn
1. Clone Repository
git clone https://github.com/DIYA73/api-auth-service.git
cd api-auth-service2. Install Dependencies
npm install3. Environment Setup
Create .env file:
# Server Configuration
NODE_ENV=development
PORT=5000
# MongoDB
MONGODB_URI=mongodb://localhost:27017/auth_service
# Or MongoDB Atlas:
# MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/auth_service
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-minimum-32-characters-long
JWT_EXPIRES_IN=7d
JWT_REFRESH_SECRET=your-refresh-token-secret-also-32-chars-min
JWT_REFRESH_EXPIRES_IN=30d
# bcrypt Configuration
BCRYPT_SALT_ROUNDS=10
# CORS Configuration
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173
# Optional: Email Service (for verification)
# EMAIL_HOST=smtp.gmail.com
# EMAIL_PORT=587
# EMAIL_USER=your-email@gmail.com
# EMAIL_PASSWORD=your-app-password4. Start Server
# Development mode (with nodemon)
npm run dev
# Production mode
npm startServer runs on http://localhost:5000
api-auth-service/
├── src/
│ ├── controllers/ # Request handlers
│ │ └── auth.controller.js
│ ├── models/ # Mongoose schemas
│ │ └── User.model.js
│ ├── routes/ # API routes
│ │ └── auth.routes.js
│ ├── middleware/ # Express middleware
│ │ ├── auth.middleware.js
│ │ ├── validate.middleware.js
│ │ └── error.middleware.js
│ ├── config/ # Configuration
│ │ ├── db.config.js
│ │ └── jwt.config.js
│ ├── utils/ # Utilities
│ │ ├── token.util.js
│ │ └── password.util.js
│ ├── validators/ # Input validation
│ │ └── auth.validator.js
│ └── server.js # Entry point
├── .env.example # Environment template
├── .gitignore
├── LICENSE
├── package.json
└── README.md
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /api/auth/register |
Register new user | No |
| POST | /api/auth/login |
User login | No |
| POST | /api/auth/refresh |
Refresh access token | Yes (Refresh Token) |
| POST | /api/auth/logout |
User logout | Yes |
| POST | /api/auth/forgot-password |
Request password reset | No |
| POST | /api/auth/reset-password |
Reset password | No |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /api/users/profile |
Get user profile | Yes |
| PUT | /api/users/profile |
Update user profile | Yes |
| PUT | /api/users/password |
Change password | Yes |
| DELETE | /api/users/account |
Delete account | Yes |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /api/admin/users |
List all users | Yes (Admin) |
| GET | /api/admin/users/:id |
Get user by ID | Yes (Admin) |
| PUT | /api/admin/users/:id/role |
Update user role | Yes (Admin) |
| DELETE | /api/admin/users/:id |
Delete user | Yes (Admin) |
// Password hashing (bcrypt)
const bcrypt = require('bcrypt');
const saltRounds = 10;
const hashPassword = async (password) => {
return await bcrypt.hash(password, saltRounds);
};
const comparePassword = async (password, hash) => {
return await bcrypt.compare(password, hash);
};const jwt = require('jsonwebtoken');
const generateToken = (userId, role) => {
return jwt.sign(
{ userId, role },
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRES_IN }
);
};const authMiddleware = async (req, res, next) => {
try {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'No token provided' });
}
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
res.status(401).json({ message: 'Invalid token' });
}
};// services/auth.service.js
const API_URL = 'http://localhost:5000/api/auth';
export const authService = {
register: async (userData) => {
const response = await fetch(`${API_URL}/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
});
return response.json();
},
login: async (credentials) => {
const response = await fetch(`${API_URL}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials)
});
const data = await response.json();
if (data.token) {
localStorage.setItem('token', data.token);
}
return data;
},
logout: () => {
localStorage.removeItem('token');
},
getProfile: async () => {
const token = localStorage.getItem('token');
const response = await fetch('http://localhost:5000/api/users/profile', {
headers: { 'Authorization': `Bearer ${token}` }
});
return response.json();
}
};import axios from 'axios';
const apiClient = axios.create({
baseURL: 'http://localhost:5000/api'
});
// Add token to all requests
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Handle token expiration
apiClient.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401) {
// Redirect to login
window.location = '/login';
}
return Promise.reject(error);
}
);Register User:
curl -X POST http://localhost:5000/api/auth/register \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"john@example.com","password":"SecurePass123!"}'Login:
curl -X POST http://localhost:5000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"john@example.com","password":"SecurePass123!"}'Get Profile (with token):
curl -X GET http://localhost:5000/api/users/profile \
-H "Authorization: Bearer YOUR_TOKEN_HERE"# Run tests
npm test
# Watch mode
npm run test:watch
# Coverage
npm run test:coverageconst userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Name is required'],
trim: true,
minlength: 2,
maxlength: 50
},
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
lowercase: true,
trim: true,
match: [/^\S+@\S+\.\S+$/, 'Please provide a valid email']
},
password: {
type: String,
required: [true, 'Password is required'],
minlength: 8,
select: false // Don't return password by default
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user'
},
isVerified: {
type: Boolean,
default: false
},
verificationToken: String,
resetPasswordToken: String,
resetPasswordExpires: Date,
lastLogin: Date,
createdAt: {
type: Date,
default: Date.now
},
updatedAt: {
type: Date,
default: Date.now
}
});Implemented:
- ✅ Password hashing with bcrypt (salt rounds: 10)
- ✅ JWT token-based authentication
- ✅ Input validation and sanitization
- ✅ Environment variable protection
- ✅ CORS configuration
- ✅ Helmet.js security headers
- ✅ Rate limiting (optional)
- ✅ HTTPS enforcement (production)
Recommended:
- Two-factor authentication (2FA)
- Account lockout after failed attempts
- IP-based access control
- Session management
- Regular security audits
- Create new Web Service
- Connect GitHub repository
- Configure:
- Build Command:
npm install - Start Command:
npm start
- Build Command:
- Add environment variables
- Deploy
heroku create api-auth-service
heroku config:set JWT_SECRET=your-secret
heroku config:set MONGODB_URI=your-mongodb-uri
git push heroku mainFROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 5000
CMD ["npm", "start"]- User registration
- User login
- JWT authentication
- Protected routes
- Password hashing
- Email verification
- Password reset flow
- Refresh token implementation
- Role-based access control
- Account deactivation
- Two-factor authentication (2FA)
- OAuth integration (Google, GitHub)
- Session management
- Rate limiting per user
- Admin dashboard API
- Audit logging
Contributions welcome! Please:
- Fork the repository
- Create a feature branch
- Write tests for new features
- Follow existing code style
- Submit a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
DIYA73
- GitHub: @DIYA73
- LinkedIn: linkedin.com/in/didi-86b00329a
- Express.js community
- MongoDB documentation
- JWT.io resources
- bcrypt library maintainers
Microservices:
- API Rate Guardian - Rate limiting service (LIVE)
- Secure Node API - API template
Full Applications:
- CoreStack SaaS - Uses this auth pattern (LIVE)
- Personal Portfolio - Implements authentication
⭐ If this auth service helps secure your apps, please star the repository!
🔐 Securing applications, one token at a time.
Made with ❤️ for secure authentication