Step-by-Step Guide to OAuth2 Token Generation and Authentication Flow
This article walks through the complete OAuth2 token generation process, covering gateway pre‑processing, client authentication, request handling, authentication object assembly, password validation, token creation, storage options, and response handling with code examples and diagrams.
⓪ Gateway Pre‑Processing
ValidateCodeGatewayFilter.java handles captcha verification, and PasswordDecoderFilter.java decrypts the front‑end encrypted password before Spring Security processes it.
POST /auth/oauth2/token?grant_type=password&scope=server HTTP/1.1
Host: pig-gateway:9999
Authorization: Basic dGVzdDp0ZXN0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
username=admin&password=YehdBPev① Client Authentication
OAuth2ClientAuthenticationFilter extracts the Basic base64(clientId:clientSecret) from the login request and validates the client against the RegisteredClientRepository (stored in the database).
③ Receiving the Login Request
OAuth2TokenEndpointFilter receives the request after client authentication performed by OAuth2ClientAuthenticationFilter.
④ Assembling the Authentication Object
AuthenticationConverter builds the appropriate authentication token based on request parameters and grant type.
⑤ Login Authentication Token
public class XXXAuthenticationToken extends OAuth2ResourceOwnerBaseAuthenticationToken {
}⑥ Authorization Call
⑦ Core Authentication Logic
Multi‑User System Matching (UserDetailsService)
Password Matching Verification
User Status Verification
⑧ User Query Logic
Various implementations for retrieving user details:
Decoupled: use Feign to query other systems and assemble UserDetails.
Simple: query the database directly in the authentication center.
⑨ Password Verification Logic
Supported encryption formats include plain text ({noop}) and encrypted text with a prefix indicating the algorithm (e.g., {bcrypt}). PasswordEncoder automatically selects the correct algorithm based on this prefix.
return new UserDetails(user.getUsername(), "{bcrypt}" + "数据库存储的密文");⑩ Generating OAuth2AccessToken
⑪ Token Persistence
The current SAS supports JDBC and in‑memory storage; the PIG extension adds Redis support.
⑫ Login Success Event Handling
Spring Event can be used to perform additional actions such as logging or personalization after a successful login.
⑬ Output Token in Response
private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) authentication;
OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters();
// Stateless: clear security context
SecurityContextHolder.clearContext();
this.accessTokenHttpResponseConverter.write(accessTokenResponse, null, httpResponse);
}The specific output format and logic are defined here.
Source code for the full implementation is available at https://github.com/pig-mesh/pig .
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.
