The Spring Security JWT token authentication flow involves several steps, typically illustrated through two main phases: Login/Token Generation and Resource Access/Token Validation.
Client Sends Credentials:1. Login/Token Generation Flow:
The client (e.g., web browser, mobile app) sends user credentials (username and password) to the Spring Boot application's authentication endpoint.
Authentication Controller:
The application's authentication controller receives these credentials.
AuthenticationManager:
The controller delegates the authentication process to theAuthenticationManager
.
AuthenticationProvider:
TheAuthenticationManager
uses anAuthenticationProvider
(often integrated withUserDetailsService
) to validate the credentials against a user store (e.g., database).
Successful Authentication:
If credentials are valid, theAuthenticationProvider
returns anAuthentication
object.
JWT Generation:
A JWT utility class or service generates a new JWT containing user details (claims) and signs it using a secret key.
Token Sent to Client:
The generated JWT is returned to the client in the authentication response.Client Sends JWT:2. Resource Access/Token Validation Flow:
For subsequent requests to protected resources, the client includes the obtained JWT, typically in theAuthorization
header as a "Bearer" token.
Spring Security Filter Chain:
The request enters the Spring Security filter chain.
JwtAuthenticationFilter:
A customJwtAuthenticationFilter
(or similar filter) intercepts the request early in the chain.
Token Extraction and Validation:
This filter extracts the JWT from the header and validates it using the secret key (e.g., signature verification, expiration check, claim validation).
User Details Loading:
If the token is valid, the filter extracts user details (e.g., username) from the token's claims and loads the fullUserDetails
object, often via aUserDetailsService
.
SecurityContextHolder:
AnAuthentication
object is created with the loadedUserDetails
and set in theSecurityContextHolder
, making the user authenticated for the current request.
Authorization:
Subsequent filters or controllers in the chain can then perform authorization checks based on the authenticated user's roles or authorities.
Access Protected Resource:
If authorization is successful, the request proceeds to the intended protected resource.
Token Invalid/Missing:
If the token is invalid, missing, or expired, theJwtAuthenticationFilter
or a subsequent filter will reject the request, typically returning an unauthorized (401) or forbidden (403) status.
Friday, 1 August 2025
The Spring Security JWT token authentication flow
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment