Overview
The Library Management API implements JWT (JSON Web Token) based authentication with Spring Security. This guide covers security configuration, JWT setup, and authorization rules.Security Architecture
The security system consists of three main components:- SecurityConfig - Defines security filter chain and authentication providers
- JwtTokenValidator - Custom filter that validates JWT tokens
- JwtUtils - Utility for creating and validating JWT tokens
JWT Configuration Properties
Required Properties
| Property | Environment Variable | Description | Example |
|---|---|---|---|
security.jwt.user.generator | user_jwt | JWT issuer identifier | library-api |
security.jwt.key.private | key_jwt | Secret key for signing tokens | your-256-bit-secret-key |
Configuration in application.properties
/workspace/source/src/main/resources/application.properties:17-18
Setting Environment Variables
The JWT secret key should be at least 256 bits (32 characters) for HMAC256 algorithm security.
Security Filter Chain
TheSecurityConfig class defines the security filter chain that processes all HTTP requests.
Defined in: /workspace/source/src/main/java/com/raven/training/config/security/SecurityConfig.java
Filter Chain Configuration
The security filter chain implements the following rules:Disable CSRF Protection
Cross-Site Request Forgery protection is disabled for stateless JWT authentication:
Define Authorization Rules
Public and protected endpoints are configured (see Authorization Rules below)
Authorization Rules
Public Endpoints (No Authentication Required)
The following endpoints are accessible without authentication:Swagger UI Documentation
/swagger-ui/**/swagger-ui.html/v3/api-docs/**/swagger-resources/**/webjars/**
Authentication Endpoints
POST /api/v1/auth/**
SecurityConfig.java:64-73
Protected Endpoints
All other endpoints require authentication:Authorization header.
JWT Token Management
Token Structure
JWT tokens created by the API include the following claims:| Claim | Description | Example |
|---|---|---|
iss (Issuer) | Token issuer from security.jwt.user.generator | library-management-api |
sub (Subject) | Username of the authenticated user | john.doe |
authorities | User roles/authorities (comma-separated) | ROLE_USER,ROLE_ADMIN |
iat (Issued At) | Token creation timestamp | 1709740800 |
exp (Expiration) | Token expiration timestamp | 1709742600 |
jti (JWT ID) | Unique token identifier (UUID) | 550e8400-e29b-41d4-a716-446655440000 |
nbf (Not Before) | Timestamp before which token is invalid | 1709740800 |
Token Expiration
Tokens are valid for 30 minutes (1,800,000 milliseconds) from creation:JwtUtils.java:59
Token Validation Process
TheJwtTokenValidator filter validates tokens on every request:
Verify Claims
Checks:
- Token issuer matches
security.jwt.user.generator - Token has not expired
- Current time is after
nbf(Not Before) claim
JwtTokenValidator.java:57-76
Authentication Components
Authentication Manager
Provides the core authentication functionality:SecurityConfig.java:90-93
Authentication Provider
Configures DAO-based authentication with custom user details service:SecurityConfig.java:103-109
Password Encoder
Uses BCrypt for password hashing:SecurityConfig.java:117-120
BCrypt automatically handles salt generation and is resistant to rainbow table attacks.
Using JWT Tokens
Obtaining a Token
Authenticate via the login endpoint:Making Authenticated Requests
Include the token in theAuthorization header:
Security Best Practices
Strong Secret Keys
- Use at least 256-bit random keys
- Rotate keys periodically
- Store in secure secret management systems
HTTPS Only
- Always use HTTPS in production
- JWT tokens in HTTP headers are visible to attackers
- Configure SSL/TLS termination
Token Expiration
- Keep token lifetimes short (current: 30 minutes)
- Implement refresh token mechanism
- Invalidate tokens on logout
Secure Storage
- Never store tokens in localStorage
- Use httpOnly cookies when possible
- Clear tokens on client-side logout
Production Configuration
Environment-Specific Settings
Additional Security Headers
Consider adding security headers configuration:Troubleshooting
401 Unauthorized - Invalid Token
401 Unauthorized - Invalid Token
403 Forbidden - Access Denied
403 Forbidden - Access Denied
Causes:
- Valid token but insufficient permissions
- Endpoint requires specific roles
- Check user authorities in token claims
- Verify endpoint authorization requirements
Missing Authorization Header
Missing Authorization Header
CORS Issues
CORS Issues
Error: CORS policy blocking requestsSolutions:
- Add CORS configuration to SecurityConfig
- Allow
Authorizationheader in CORS settings - Configure allowed origins properly
Related Configuration
- Database Configuration - Database connection setup
- Application Properties - Complete properties reference
- Authentication Endpoints - API endpoints for login/registration