Should you at least know how to set up a simple OAuth2 authentication server before reading this article
What is token enhancement
In fact, token enhancement means that we can do some additional operations based on tokens. For example, we need to return user information to the front end when the user visits the authentication and authorization endpoint
Spring Cloud OAuth2 TokenEnhancer TokenEnhancer TokenEnhancer TokenEnhancer TokenEnhancer TokenEnhancer TokenEnhancer
If you are not familiar with spring Cloud OAuth2 token generation process, you can take a look at my Spring Cloud Oauth token generation source code parsing
The following is a small piece of code in the token creation process, and it is the last line that we need to focus on
private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString()); int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request()); if (validitySeconds > 0) { token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L))); } token.setRefreshToken(refreshToken); token.setScope(authentication.getOAuth2Request().getScope()); TokenEnhancer = TokenEnhancer; TokenEnhancer = TokenEnhancer; TokenEnhancer = TokenEnhancer; TokenEnhancer = TokenEnhancer; = null ? accessTokenEnhancer.enhance(token, authentication) : token; }Copy the code
How to customize TokenEnhancer
- Custom LwTokenEnhancer implements the TokenEnhancer interface to implement the Enhance method
- OAuth2Authentication object contains the front request parameters, and ClientDtails information and user information, we through OAuth2Authentication. GetUserAuthentication method to get the user information, The user information is then put into the map and finally passed into the token
public class LwTokenEnhancer implements TokenEnhancer { @Override public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) { Authentication authentication = oAuth2Authentication.getUserAuthentication(); final Map<String, Object> additionalInfo = new HashMap<>(8); additionalInfo.put(SecurityConstants.USER_INFO, authentication.getPrincipal()); ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(additionalInfo); return oAuth2AccessToken; }}Copy the code
- What do we need to do after we complete our custom TokenEnhancer
- Define TokenService service, add custom LwTokenEnhancer to TokenService,
- Inject tokenService into the token access endpoint
/ * * * * * token access endpoint @ param endpoints * / @ Override public void the configure (AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.allowedTokenEndpointRequestMethods(HttpMethod.POST, HttpMethod. GET). The authenticationManager (authenticationManagerBean). TokenServices (tokenServices ()) / / custom token service .tokenStore(tokenStore) // Custom token storage policy. UserDetailsService (lwUserDetailsService); / / the custom user load} / token service * * * * * @ param endpoints * / @ Bean public AuthorizationServerTokenServices tokenServices () { DefaultTokenServices services = new DefaultTokenServices(); services.setSupportRefreshToken(true); / / enabled the refresh token services. SetClientDetailsService (clientDetailsService); / / loading ways of the custom client services. SetAuthenticationManager (authenticationManagerBean); // Inject the authentication manager services.setTokenStore(tokenStore); TokenEnhancerChain = new TokenEnhancerChain(); TokenEnhancerChain(); chain.setTokenEnhancers(Arrays.asList(lwTokenEnhancer,jwtAccessTokenConverter)); / / by JWTtoken way enhanced services. SetTokenEnhancer (chain); // Set token enhancer return services; }Copy the code
rendering
- If you access the /oauth/token endpoint without enhancing it, UserInfo will not be returned.
- By implementing a custom TokenEnhancer, user information can be returned directly to the front end during authentication