2

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?

acsam
  • 63
  • 1
  • 8

3 Answers3

2

In case you are using the new authorization server then creating this bean will help you achieve your goal. The good thing, once the bean is detected it will automatically be applied.

@Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
        return context -> {
            Authentication principal = context.getPrincipal();
            //context.getTokenType().getValue().equals("access_token")
            if (Objects.equals(context.getTokenType().getValue(), "access_token") && principal instanceof UsernamePasswordAuthenticationToken) {
                Set<String> authorities = principal.getAuthorities().stream()
                        .map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
                User user = (User) principal.getPrincipal();
                context.getClaims().claim("authorities", authorities)
                        .claim("user", user);
            }
        };
    }

Duplicate of How to create custom claims in JWT using spring-authorization-server

  • I am using the new authorization server, and the snippet you provided will add the additional parameters inside the claim, not outside. I wanted my parameters outside the jwt – acsam Jan 23 '22 at 19:01
2

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.

acsam
  • 63
  • 1
  • 8
-2

enter image description here

This class and the method maybe help you.You can find the class init place

liuxiuxue
  • 39
  • 2
  • please do not upload images of code, that is against the rules https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question – Toerktumlare Jan 22 '22 at 12:07