Creating a highly secure application login API in Node.js involves several layers of security measures to protect against common vulnerabilities. Below is a comprehensive setup combining technologies and best practices:
1. Environment Setup
- Node.js: Ensure you have an updated LTS version of Node.js.
- Express.js: A popular web framework for Node.js.
- HTTPS: Set up your server to support HTTPS to encrypt data in transit.
2. Dependencies
Install essential libraries:
express: To set up the web server.
bcrypt: For hashing passwords.
jsonwebtoken: For creating JSON Web Tokens for session management.
helmet: To secure the app by setting various HTTP headers.
dotenv: For managing environment variables.
csurf: For CSRF protection.
express-rate-limit: To prevent brute force attacks.
validator: To sanitize and validate inputs.
express-session and/or redis: To manage sessions, when required.
npm install express bcrypt jsonwebtoken helmet dotenv csurf express-rate-limit validator express-session redis
3. Best Practices
Password Handling
- Hashing: Use
bcrypt to hash passwords before storing them in the database.
- Salting: Automatically handled by
bcrypt, which increases security by adding a unique value to each password before hashing.
const bcrypt = require('bcrypt');
const saltRounds = 10;
async function hashPassword(password) {
return await bcrypt.hash(password, saltRounds);
}
async function comparePassword(plainPassword, hash) {
return await bcrypt.compare(plainPassword, hash);
}
Authentication
- JWT (JSON Web Tokens): Use JWT for stateless authentication, or session cookies for stateful authentication.
- Expiration: Make sure JWTs have a short expiration time.
const jwt = require('jsonwebtoken');
function generateAccessToken(user) {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '15m' });
}
Input Validation and Sanitization
- Use
validator to sanitize and validate inputs to prevent SQL Injection and XSS attacks.
const { check, validationResult } = require('express-validator');
app.post('/api/login', [
check('email').isEmail().normalizeEmail(),
check('password').isLength({ min: 6 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Continue with authentication
});
Rate Limiting
- Implement rate limiting to protect against brute force attacks.
const rateLimit = require('express-rate-limit');
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per window
message: "Too many login attempts from this IP, please try again later."
});
app.use('/api/login', loginLimiter);
Cross-Origin Resource Sharing (CORS)
- Configure CORS to limit resources that can be requested from your server.
const cors = require('cors');
app.use(cors({
origin: 'https://yourdomain.com',
optionsSuccessStatus: 200
}));
Security Headers
- Use
helmet for setting secure HTTP headers, such as Content-Security-Policy, X-Content-Type-Options, X-XSS-Protection, and others.
const helmet = require('helmet');
app.use(helmet());
CSRF Protection
- Use
csurf to protect against cross-site request forgery.
const csurf = require('csurf');
app.use(csurf());
app.use((req, res, next) => {
res.locals.csrfToken = req.csrfToken();
next();
});
Session Management
- Securely manage sessions if JWTs are not used. Use
express-session with options like httpOnly, secure, sameSite, and more.
4. Final Steps
- HTTPS: Always use HTTPS in production to encrypt data in transit.
- Secrets Management: Use environment variables to store sensitive data like JWT secrets. Utilize
dotenv to manage them.
- Monitoring: Implement logging and monitoring for suspicious activities using tools like
winston or morgan.
This setup should provide a strong foundation for a secure login API in Node.js. Always stay updated with the latest security practices and Node.js updates.