Overview
Sistema de Productos implements multiple security layers to protect user data and prevent unauthorized access. This guide covers authentication, authorization, password security, and best practices.Authentication
JWT Token-Based Authentication
The application uses JSON Web Tokens (JWT) for stateless authentication:server/helpers/auth.js
Tokens expire after 5 hours, requiring users to re-authenticate. This limits the window of opportunity if a token is compromised.
Token Verification
All protected routes verify tokens using the authentication middleware:server/middlewares/auth.js
Token Verification
Verifies the token signature using the JWT_SECRET to ensure it hasn’t been tampered with.
HTTP-Only Cookies
Secure Cookie Configuration
Tokens are stored in HTTP-only cookies to prevent JavaScript access:server/controllers/usuarios.controller.js
Cookie Security Properties
httpOnly
httpOnly
Prevents client-side JavaScript from accessing the cookie, protecting against XSS attacks. Even if an attacker injects malicious JavaScript, they cannot steal the authentication token.
secure
secure
When set to
true, ensures cookies are only transmitted over HTTPS connections. This prevents man-in-the-middle attacks from intercepting authentication tokens.sameSite
sameSite
Controls when cookies are sent with cross-site requests:
strict: Cookie never sent in cross-site requestslax: Cookie sent with top-level navigations (default, good balance)none: Cookie sent with all requests (requiressecure: true)
Password Security
Bcrypt Password Hashing
Passwords are hashed using bcrypt with a cost factor of 10:Why Bcrypt?
Adaptive Hashing
The cost factor (10) determines the computational cost. As hardware improves, you can increase this value to maintain security.
Built-in Salt
Bcrypt automatically generates and includes a unique salt for each password, preventing rainbow table attacks.
Role-Based Access Control (RBAC)
Authorization Middleware
The system implements role-based access control with two roles: Administrator and regular users:server/middlewares/auth.js
Protected Routes
Routes are protected using middleware chains:server/routes/usuarios.routes.js
Middleware is applied in order. First,
auntenticarToken verifies the user is logged in, then autenticarAdministrador checks for admin privileges.API Security Best Practices
1. Input Validation
Always validate and sanitize user input:2. SQL Injection Prevention
Use parameterized queries (already implemented):3. Rate Limiting
Implement rate limiting to prevent brute-force attacks:4. CORS Configuration
Restrict cross-origin requests to trusted domains:server/app.js
5. Environment Variables
Never hardcode secrets. Always use environment variables:6. Error Handling
Don’t leak sensitive information in error messages:Security Checklist
Environment Security
- Use strong, unique JWT_SECRET (minimum 64 characters)
- Never commit
.envfiles to version control - Use different secrets for development and production
- Rotate secrets regularly
Authentication
- Implement token expiration (5 hours or less)
- Use HTTP-only cookies for token storage
- Enable
secureflag for cookies in production - Implement logout functionality
- Verify user exists on each authenticated request
Password Security
- Use bcrypt with cost factor ≥ 10
- Enforce minimum password length (8+ characters)
- Implement password complexity requirements
- Secure password reset mechanism with email verification
Authorization
- Implement role-based access control
- Protect admin routes with authorization middleware
- Verify permissions on every protected endpoint
API Security
- Use parameterized queries for database operations
- Validate and sanitize all user input
- Implement rate limiting on sensitive endpoints
- Configure CORS to allow only trusted origins
- Use HTTPS in production
Security Headers
Add security headers to protect against common attacks:server/app.js
Monitoring and Auditing
Logging Security Events
Database Audit Trail
The database includes timestamp fields for auditing:Track when records are created and updated to detect suspicious activity or unauthorized changes.
Incident Response
If a security incident occurs:Immediate Actions
- Rotate JWT_SECRET immediately
- Invalidate all existing tokens
- Force all users to re-authenticate
- Review access logs for suspicious activity
Investigation
- Identify the scope of the breach
- Determine what data was accessed
- Check for unauthorized database changes
- Review recent deployments and code changes
Remediation
- Patch vulnerabilities
- Update dependencies
- Strengthen security measures
- Notify affected users if necessary
