Authentication, Authorization, and Security
Implement secure authentication, authorization, password handling, JWT-based APIs, cookies, CSRF protection, input validation, and security best practices.
Password Hashing and JWT Authentication
Passwords should never be stored as plaintext. Password hashing algorithms such as Argon2 or bcrypt are designed to make password guessing computationally expensive.
JSON Web Tokens can carry signed claims between systems. A JWT can be useful for stateless API authentication, but token storage, expiration, rotation, revocation, audience validation, and signing-key management must be designed carefully.
Always verify the signature and validate relevant claims such as issuer, audience, expiration, and intended use.
import jwt from 'jsonwebtoken';
function authenticate(req, res, next) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ error: 'Missing token' });
}
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}- Never store plaintext passwords.
- JWT verification must validate both the signature and security-relevant claims.
- Short-lived access tokens and controlled refresh-token strategies reduce risk.
How should user passwords be stored?
Common Web Security Risks
Node.js APIs must defend against common web vulnerabilities including injection, broken access control, cross-site scripting, CSRF, insecure deserialization, credential leakage, and denial-of-service conditions.
Validate input at trust boundaries, use parameterized database operations, enforce authorization server-side, apply rate limits where appropriate, configure secure cookies, and use HTTPS in production.
- Treat every client input as untrusted.
- Authorization must be enforced on the server.
- Security headers, rate limiting, input validation, and secure secret handling are essential production practices.
Where should authorization checks ultimately be enforced?