Demystifying Spring Security OAuth: Core Classes and Token Generation Flow
This article walks through Spring Security OAuth's core classes, explaining how the TokenEndpoint processes /oauth/token requests, validates client details, builds TokenRequests, delegates to TokenGranters, and ultimately generates and returns an OAuth2 access token.
Spring Security OAuth Core Class Diagram Analysis
Spring Security OAuth handles OAuth2 token issuance; the entry point is TokenEndpoint which processes requests to /oauth/token. It first retrieves client details via ClientDetailsService, builds a TokenRequest, and delegates to a TokenGranter based on the grant_type.
The TokenGranter creates an OAuth2Authorization that combines OAuth2Request (client and request data) and Authorization (user information). This object is passed to AuthorizationServerTokenServices to produce an OAuth2AccessToken.
During the request, the framework validates clientId, scope, grant_type, and ensures the grant mode matches the configured client. For the password grant, ResourceOwnerPasswordTokenGranter authenticates the user via PigxUserDetailsServiceImpl and builds the authentication object.
public TokenRequest createTokenRequest(Map<String, String> requestParameters, ClientDetails authenticatedClient) {
String clientId = requestParameters.get(OAuth2Utils.CLIENT_ID);
if (clientId == null) {
clientId = authenticatedClient.getClientId();
} else {
if (!clientId.equals(authenticatedClient.getClientId())) {
throw new InvalidClientException("Given client ID does not match authenticated client");
}
}
String grantType = requestParameters.get(OAuth2Utils.GRANT_TYPE);
Set<String> scopes = extractScopes(requestParameters, clientId);
TokenRequest tokenRequest = new TokenRequest(requestParameters, clientId, scopes, grantType);
return tokenRequest;
}Token creation ultimately calls DefaultTokenServices.createAccessToken, which checks the token store for existing tokens, handles expiration, generates a new UUID‑based token, sets its expiration, refresh token, and scope, and optionally applies a TokenEnhancer.
protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {
return tokenServices.createAccessToken(getOAuth2Authentication(client, tokenRequest));
}The process concludes with the token being written to the HTTP response.
Java Architecture Diary
Committed to sharing original, high‑quality technical articles; no fluff or promotional content.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
