public class LoyaltyGroupTokenEnhancer extends AbstractUserTokenEnhancer {
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken,
OAuth2Authentication authentication) {
if (hasAuthenticatedUser(authentication)) {
// do nothing if no user authentication
return accessToken;
}
// Call to AbstractUserTokenEnhancer#getUser to retrieve user stored in the current request scope
User user = super.getUser(authentication);
Object loyaltyGroup = user.getAttribute("mycompany_loyalty_group");
if(loyaltyGroup == null) {
return accessToken;
}
// Convenience method. Allows us to add new values to the map returned
// by DefaultOAuth2AccessToken#getAdditionalInformation, as the default
// map is read-only.
DefaultOAuth2AccessToken enhanceableToken = TokenEnhancerUtil.getEnhanceableToken(accessToken);
Map<String, Object> claims = enhanceableToken.getAdditionalInformation();
// Enhance our token with the new claim without overwriting existing claims
Collection<String> loyaltyGroups = claims.getAttribute("loyalty_groups");
if(loyaltyGroups == null) {
loyaltyGroups = new HashSet<>();
}
loyaltyGroups.add(loyaltyGroup);
claims.put("loyalty_groups", loyaltyGroups);
return enhancedToken;
}
}