Search code examples
springspring-bootspring-securityspring-security-oauth2

Spring Authorization server customizing the access token response to add additional params


I am implementing the spring authorization server and I want to add few custom properties to the token response json. Below is how I want the response to be.

{
    "access_token": *jwt*,
    "scope": "articles.read openid",
    "token_type": "Bearer",
    "expires_in": 299,
    ***"customvalue1":99***
}

I have seen multiple posts in stack overflow where similar topic is discussed, but in those scenarios the additional data is added either to the claim or header of jwt. My requirement is to add it outside of the jwt. I tried to implement OAuth2TokenCustomizer, but this allows only the claims or headers of the jwt to be modified. Can anyone pls help?


Solution

  • To anyone coming here looking for answer:

    I ended up overriding OAuth2TokenEndpointFilter. It has a authentication successhandler which can be injected to perform any additional token response manipulation.

       @Bean
        public Customizer<OAuth2TokenEndpointConfigurer> customizeTokenEndpoint() {
            return tokenEndpoint -> tokenEndpoint
                    .accessTokenResponseHandler(success());
        }
          @Bean(name = "token")
        public AuthenticationSuccessHandler success() {
            return new TokenResponseSuccessHandler();
        }
    

    Then inside success handler,

    @Override
           public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
        final OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) authentication;
        ******
        ** 
    
           Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters();
                    if(additionalParameters.size()==0)
                        additionalParameters=new HashMap<>();
                 additionalParameters.put("hi","hi");
    

    Finally use, OAuth2AccessTokenResponse.Builder to build a new response.