Key Features of Spring Boot Security
- Authentication and Authorization:
- Authentication: Verifying the identity of a user (e.g., username and password).
- Authorization: Controlling access to resources based on roles or permissions.
- Built-in Security Mechanisms:
- Basic Authentication
- Form-based Authentication
- OAuth 2.0 / OpenID Connect
- JWT (JSON Web Token) Authentication
- LDAP (Lightweight Directory Access Protocol) integration
- CSRF Protection:
- Mitigates cross-site request forgery attacks by validating user actions through CSRF tokens.
- Default Secure Configurations:
- By default, Spring Security secures all application endpoints and provides a basic login form or HTTP Basic Authentication.
- Integration with Spring Ecosystem:
- Works seamlessly with Spring Boot, Spring MVC, Spring Data, and other Spring modules.
- Highly Customizable:
- Developers can override default security settings to define custom access rules, login/logout mechanisms, and more.
JWT Concepts in Detail
JSON Web Tokens (JWT) are a compact, URL-safe way to represent claims between two parties. They are commonly used for authentication and authorization in web applications.
Structure of JWT
A JWT consists of three parts, separated by dots (.):
Header. Payload. Signature
- Header: Contains metadata about the token, including the signing algorithm used (e.g., HS256).
{
"alg": "HS256",
"typ": "JWT"
}
Payload: Contains claims, which are statements about an entity (e.g., user details or permissions).
Example claims:
{
"sub": "1234567890",
"name": "John Doe",
"role": "admin",
"iat": 1516239022,
"exp": 1516242622
}
Signature: Ensures the token is not tampered with. It is created by signing the header and payload using a secret key or a private key.
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
1. First Request: User Login
Request Flow
- User sends credentials: The client (e.g., a React or Angular frontend) sends a POST request to the /auth/login endpoint with the username and password.
- URL: /auth/login
- HTTP Method: POST
- Request Body:
{
"username": "user@example.com",
"password": "password123"
}
- Server validates credentials:
- Spring Security's AuthenticationManager is used to validate the username and password.
- If valid, a JWT token is generated.
- Server responds with JWT:
- The server returns a JWT token in the response body, which the client stores (e.g., in local storage or cookies).
Response Example
{
"token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyQGV4YW1wbGUuY29tIiwicm9sZXMiOlsiUk9MRV9VU0VSIl0sImV4cCI6MTY5MTIwMTAwMH0.TcNs3yRGQ87A..."
}
2. Subsequent Requests with JWT
Request Flow
- Client includes JWT in requests:
- The client includes the JWT token in the Authorization header:
For example, accessing a protected endpoint /users/me:
- URL: /users/me
- HTTP Method: GET
- Headers:
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyQGV4YW1wbGUuY29tIiwicm9sZXMiOlsiUk9MRV9VU0VSIl0sImV4cCI6MTY5MTIwMTAwMH0...
2 Server validates the token:
- A Spring Security filter chain intercepts the request.
- The JwtAuthenticationFilter checks the Authorization header for the token.
- The token is parsed and validated using the signing key.
- If valid, user details (like username and roles) are extracted and added to the SecurityContext.
3 Server processes the request:
- The request proceeds to the controller or service layer.
- Access is granted or denied based on roles or permissions.
3. Token Expiry and Refresh
Token Expiry
- Tokens are issued with an expiry time (exp claim).
- When the token expires, the client receives an HTTP 401 Unauthorized response.
Token Refresh
- The client uses a refresh token (a longer-lived JWT or separate token) to obtain a new access token from a /auth/refresh endpoint.
Spring Security 6.1 Implementation with Internal Classes
Key Components
- AuthenticationManager: Validates user credentials.
- FilterChainProxy: Handles the filter chain for incoming requests.
- OncePerRequestFilter: Custom filter for JWT validation.
Code Implementation
1. AuthenticationManager and Security Configuration
Thank You for Your Support! 🙏
Your encouragement keeps us going!
If you find value in our content, please consider supporting us.
💡 Even a small contribution can make a big difference in helping us build better educational resources.
Donate Now