JWT Security
JSON Web Tokens (JWT) are the primary authentication mechanism in the Authorization Service. Proper JWT configuration is critical for system security.JWT Secret Management
TheJWT_SECRET environment variable is used to sign and verify all tokens. This secret must be:
- At least 256 bits (32 bytes) for HS256 algorithm
- Random and unpredictable - use cryptographically secure random generation
- Never committed to version control - use secrets management systems
- Rotated periodically - implement a key rotation strategy
Generating a Secure Secret
Using OpenSSL:Token Expiration Strategy
TheJWT_EXPIRATION_MS controls how long tokens remain valid. Consider the security/usability tradeoff:
| Environment | Recommended Expiration | Rationale |
|---|---|---|
| Development | 24 hours (86400000ms) | Convenience for testing |
| Staging | 4 hours (14400000ms) | Balance testing and security |
| Production | 1 hour (3600000ms) | Minimize token exposure |
| Mobile Apps | 7 days with refresh | User experience on trusted devices |
JwtUtil.java:24-27):
Token Claims
The service includes the following claims in each JWT:sub(subject) - User’s email addressuserId- Internal user IDemail- User’s email (duplicate for convenience)roles- Array of role namespermissions- Flattened array of all permissions from all rolesiat(issued at) - Token creation timestampexp(expiration) - Token expiration timestamp
JwtUtil.java:30-56):
Permissions are flattened into the token to avoid additional database lookups on each request. This improves performance but means permission changes require a new token.
Token Validation
TheJwtAuthenticationFilter validates tokens on every protected request:
- Extract token from
Authorization: Bearer <token>header - Verify signature using the shared secret
- Check expiration timestamp
- Load user details and permissions
- Set Spring Security context
JwtUtil.java:72-79):
Password Security
Password Hashing
All passwords are hashed using BCrypt with default work factor (10 rounds). BCrypt is specifically designed for password hashing and includes:- Automatic salt generation - Each password gets a unique salt
- Adaptive cost - Can increase work factor as hardware improves
- Slow by design - Resistant to brute-force attacks
SecurityConfig.java:54-56):
Password Policy Recommendations
While the service doesn’t enforce password complexity by default, implement these policies at the application layer:- Minimum length: 12 characters
- Complexity: Mix of uppercase, lowercase, numbers, and symbols
- No common passwords: Check against lists like “Have I Been Pwned”
- No password reuse: Track password history
- Regular rotation: Encourage (but don’t force) periodic changes
Role-Based Access Control (RBAC)
Authorization Model
The service implements a hierarchical RBAC system:- Users can have multiple roles
- Roles contain multiple permissions
- Permissions are grouped by modules (USERS, ROLES, AUDIT, etc.)
Method-Level Security
Use Spring Security’s@PreAuthorize annotation to protect controller methods:
Dynamic Permission Checking
For complex authorization logic, injectAuthPrincipal in your service layer:
HTTPS Configuration
Why HTTPS is Essential
Enabling HTTPS in Spring Boot
Generate a keystore (for testing only):application.properties:
Production HTTPS Deployment
For production, use a reverse proxy (Nginx, Apache) with a certificate from:- Let’s Encrypt (free, automated)
- Your organization’s PKI
- Commercial CA (DigiCert, Sectigo, etc.)
CORS Configuration
If your frontend is hosted on a different domain, configure CORS carefully:Database Security
Principle of Least Privilege
Create a dedicated database user with minimal permissions:Connection Security
For remote databases, use SSL/TLS:Sensitive Data Protection
Consider encrypting sensitive columns:- Email addresses
- Phone numbers
- Personal information
Audit Logging
The service includes comprehensive audit logging using AOP (@AuditLog annotation):
What is logged:
- User performing the action
- Action type (CREATE, UPDATE, DELETE, etc.)
- Module (USERS, ROLES, PERMISSIONS, etc.)
- IP address
- Timestamp
- Method arguments (sanitized)
- Success/failure status
ActivityLogEntity):
activity_logs table and can be queried via:
Security Checklist
Before deploying to production:- Strong
JWT_SECRETconfigured (at least 256 bits) - Appropriate
JWT_EXPIRATION_MSset (≤ 1 hour recommended) - HTTPS enabled with valid certificate
- Database credentials stored in secrets manager
- Database user has minimal required permissions
- CORS configured with specific origins (no wildcards)
-
spring.jpa.show-sql=falsein production - Password policy enforced at application layer
- Audit logging enabled and monitored
- Rate limiting implemented (consider Spring Cloud Gateway)
- Security headers configured (CSP, HSTS, X-Frame-Options)
- Dependency scanning enabled (Snyk, OWASP Dependency-Check)
- Regular security updates applied
Security Incident Response
If you suspect a security breach:- Rotate JWT secret immediately - invalidates all existing tokens
- Force password reset for affected users
- Review audit logs - check
activity_logstable for suspicious activity - Check database access logs - identify unauthorized queries
- Update dependencies - patch any known vulnerabilities
- Notify users - inform affected parties per your disclosure policy
Next Steps
Configuration Guide
Learn how to configure environment variables and database settings
Error Handling
Understand error responses and common troubleshooting scenarios