Overview
The Library API uses Spring Security to protect endpoints and manage authentication. This guide covers the security architecture, configuration, and best practices.Security Architecture
The application implements the following security features:HTTP Basic Authentication
Stateless authentication using HTTP Basic Auth headers
Password Encryption
BCrypt password hashing with strength factor 12
Session Management
Stateless sessions for REST API design
Endpoint Protection
Role-based access control for API endpoints
Spring Security Configuration
The security configuration is defined inSecurityConfig.java:
SecurityConfig.java
Configuration Breakdown
Configure HTTP Security
Define which endpoints require authentication:
- Public endpoints:
/,/auth/login,/home,/auth/register - Protected endpoints: All other endpoints require authentication
Password Encryption
The application uses BCrypt for password hashing with a strength factor of 12.BCrypt Configuration
SecurityConfig.java
Understanding BCrypt Strength
The BCrypt work factor determines computational cost:
- 4-10: Fast, suitable for testing (not recommended for production)
- 12: Balanced security and performance (recommended)
- 13-15: Higher security, slower performance
- 16+: Very secure, but significantly slower
Encrypting Passwords
When creating or updating users, always encrypt passwords:UserService.java
Validating Passwords
To verify a password during authentication:AuthService.java
Authentication Setup
Authentication Provider
The application uses aDaoAuthenticationProvider for database-backed authentication:
SecurityConfig.java
Authentication Manager
The authentication manager coordinates authentication providers:SecurityConfig.java
UserDetailsService
The application uses an in-memory user store (can be replaced with database-backed implementation):SecurityConfig.java
For production, implement a custom
UserDetailsService that loads users from the database.Implementing Database-Backed Authentication
Replace the in-memory user store with database authentication:Create UserDetailsService implementation
Create a custom service that loads users from the database:
CustomUserDetailsService.java
Protecting Endpoints
Public vs Protected Endpoints
Configure which endpoints are public and which require authentication:SecurityConfig.java
Role-Based Access Control
Implement role-based authorization:SecurityConfig.java
Method-Level Security
Protect individual methods with annotations:Making Authenticated Requests
Using cURL
Using JavaScript/Fetch
Using Postman
CSRF Protection
The current implementation does not explicitly disable CSRF protection. For stateless REST APIs, you may want to disable it.
SecurityConfig.java
CORS Configuration
CORS is not configured in the current implementation. If your API needs to be accessed from web browsers on different domains, add this configuration.
CorsConfig.java
Security Best Practices
Use HTTPS
Always use HTTPS in production to encrypt credentials in transit. HTTP Basic Auth sends credentials in base64 encoding, which is easily decoded.
Strong Passwords
Enforce password policies: minimum length, complexity requirements, and password history.
Rate Limiting
Implement rate limiting to prevent brute force attacks on authentication endpoints.
Audit Logging
Log authentication attempts, especially failures, for security monitoring.
Token Expiration
Consider implementing JWT tokens with expiration for better security than persistent Basic Auth.
Input Validation
Validate and sanitize all user inputs to prevent injection attacks.
Troubleshooting
401 Unauthorized
401 Unauthorized
403 Forbidden
403 Forbidden
Error: Authenticated but access denied (403)Solutions:
- Verify user has the required role for the endpoint
- Check the endpoint’s security configuration
- Ensure roles are properly assigned to the user
CORS errors
CORS errors
Error: CORS policy blocking requests from browserSolutions:
- Configure CORS to allow your frontend origin
- Ensure
allowCredentials(true)is set if sending credentials - Check allowed methods include the HTTP method you’re using
Password not matching
Password not matching
Error: Correct password not workingSolutions:
- Verify password was encrypted before saving:
passwordEncoder.encode(password) - Check BCrypt encoder is being used for validation
- Ensure the same BCrypt strength is used for encoding and validation
- Verify the stored password hash starts with
$2a$or$2b$(BCrypt format)
Session issues
Session issues
Error: Session-related errors in stateless APISolutions:
- Ensure
SessionCreationPolicy.STATELESSis configured - Don’t rely on session storage in your application code
- Send authentication credentials with every request
Advanced Security Topics
JWT Authentication
Consider implementing JWT tokens for better scalability and stateless authentication.
OAuth 2.0
Integrate OAuth 2.0 for third-party authentication (Google, GitHub, etc.).
Two-Factor Auth
Add 2FA for enhanced security on sensitive operations.
API Key Authentication
Implement API keys for service-to-service authentication.
Next Steps
API Reference
Explore the protected API endpoints
User Management
Learn about user management endpoints