The Spring Security JWT token authentication flow involves several steps, typically illustrated through two main phases: Login/Token Generation and Resource Access/Token Validation.
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.
- The application's authentication controller receives these credentials.
- The controller delegates the authentication process to the
AuthenticationManager
. - The
AuthenticationManager
uses anAuthenticationProvider
(often integrated withUserDetailsService
) to validate the credentials against a user store (e.g., database). - If credentials are valid, the
AuthenticationProvider
returns anAuthentication
object. - A JWT utility class or service generates a new JWT containing user details (claims) and signs it using a secret key.
- The generated JWT is returned to the client in the authentication response.
2. Resource Access/Token Validation Flow:
- For subsequent requests to protected resources, the client includes the obtained JWT, typically in the
Authorization
header as a "Bearer" token. - The request enters the Spring Security filter chain.
- A custom
JwtAuthenticationFilter
(or similar filter) intercepts the request early in the chain. - This filter extracts the JWT from the header and validates it using the secret key (e.g., signature verification, expiration check, claim validation).
- If the token is valid, the filter extracts user details (e.g., username) from the token's claims and loads the full
UserDetails
object, often via aUserDetailsService
. - An
Authentication
object is created with the loadedUserDetails
and set in theSecurityContextHolder
, making the user authenticated for the current request. - Subsequent filters or controllers in the chain can then perform authorization checks based on the authenticated user's roles or authorities.
- If authorization is successful, the request proceeds to the intended protected resource.
- If the token is invalid, missing, or expired, the
JwtAuthenticationFilter
or a subsequent filter will reject the request, typically returning an unauthorized (401) or forbidden (403) status.