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