Creating a highly secure login API in Node.js involves several layers of security across authentication, authorization, data validation, and protection against common web vulnerabilities. Here’s a comprehensive example of how to structure such an API using various technologies and best practices:
Overview
- Environment Setup
- User Authentication with JWT
- Secure Password Handling
- Input Validation and Sanitization
- Rate Limiting
- Error Handling
- Security Headers and CORS
- HTTPS and Secure Cookies
- Logging and Monitoring
1. Environment Setup
Set up a Node.js application with necessary dependencies:
npm init -y
npm install express bcryptjs jsonwebtoken dotenv helmet cors express-rate-limit validator mongoose
2. User Authentication with JWT
Using JSON Web Tokens (JWT) for stateless authentication.
// .env
JWT_SECRET='your-secret-key'
// server.js
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const helmet = require('helmet');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const loginRoute = require('./routes/loginRoute');
const app = express();
app.use(express.json());
app.use(helmet());
app.use(cors({ origin: 'your-frontend-domain.com', optionsSuccessStatus: 200 }));
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/secureapp', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Rate Limiter
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
});
app.use(limiter);
// Routes
app.use('/api/v1/auth', loginRoute);
// Error handling middleware
app.use((err, req, res, next) => {
res.status(500).json({ message: 'Internal Server Error' });
});
// Start the server
app.listen(3000, () => {
console.log('Server running on port 3000');
});
3. Secure Password Handling
Using bcryptjs for hashing passwords.
// models/User.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
UserSchema.pre('save', async function (next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 12);
next();
});
UserSchema.methods.comparePassword = async function (candidatePassword) {
return bcrypt.compare(candidatePassword, this.password);
};
module.exports = mongoose.model('User', UserSchema);
4. Login Route with JWT
// routes/loginRoute.js
const express = require('express');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const { body, validationResult } = require('express-validator');
const router = express.Router();
// POST /api/v1/auth/login
router.post('/login',
body('email').isEmail(),
body('password').isLength({ min: 5 }),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user || !(await user.comparePassword(password))) {
return res.status(401).json({ message: 'Invalid credentials' });
}
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, {
expiresIn: '1h',
});
res.json({ token });
} catch (error) {
res.status(500).json({ message: 'Internal Server Error' });
}
}
);
module.exports = router;
5. Input Validation and Sanitization
Already demonstrated in the login route using express-validator for sanitizing and validating user input.
6. Rate Limiting
Implemented using express-rate-limit to prevent brute force attacks.
7. Error Handling
Centralized error handling middleware is provided in Express app setup.
8. Security Headers and CORS
Configured using helmet and cors to secure HTTP headers and handle cross-origin requests appropriately.
9. HTTPS and Secure Cookies
Ensure the app is deployed behind an HTTPS server or a reverse proxy like Nginx that handles HTTPS. Use secure cookies for session management if needed.
app.use(require('cookie-session')({
name: 'session',
keys: [process.env.COOKIE_SECRET],
secure: true, // Ensures the browser only sends the cookie over HTTPS
}));
10. Logging and Monitoring
Implement logging for monitoring and debugging using tools like winston or morgan for HTTP request logging.
npm install morgan
// server.js
const morgan = require('morgan');
// Using morgan
app.use(morgan('combined'));
Pro Tips
- Regular Security Audits: Regularly audit your codebase for security vulnerabilities.
- Dependency Updates: Keep dependencies up to date to mitigate known vulnerabilities.
- Use Strong Secrets: Use a strong, randomly generated secret for JWT and secure cookie storage.
- API Documentation: Document your API endpoints thoroughly to ensure consistent and secure usage.
By implementing these strategies and technologies, you can significantly enhance the security posture of your Node.js application login API.