Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm building an OAuth2 authorization server based on the experimental Spring project Spring Authorization Server

My use case is quite simple, fetch users from a DB, and based on some properties of the user, set some custom claims in the JWT being produced. I haven't found a way to do so with Spring Authorization Server, the only way I could work out is to inject a jwtCustomizer object as part of the JwtEncoder bean definition:

  @Bean
  public JwtEncoder jwtEncoder(CryptoKeySource keySource) {
    NimbusJwsEncoder jwtEncoder = new NimbusJwsEncoder(keySource);
    jwtEncoder.setJwtCustomizer((headersBuilder, claimsBuilder) -> {
      // Inject some headers and claims...
    });
    return jwtEncoder;
  }

This obviously doesn't give me access to users information, therefore I can't set the claims I need at this point. Did anyone manage to solve this problem?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
351 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can try following way. Though it is Kotlin code, not Java, but approach should be clear:

import org.springframework.security.oauth2.provider.token.TokenEnhancer

class UserTokenEnhancer : TokenEnhancer {
    
    override fun enhance(accessToken: OAuth2AccessToken,
                         authentication: OAuth2Authentication): OAuth2AccessToken {

        val username = authentication.userAuthentication.name
        val additionalInfo = mapOf( /* populate with some data for given username */ )

        (accessToken as DefaultOAuth2AccessToken).additionalInformation = additionalInfo
        return accessToken
    }
}

Then just register bean:

@Bean
fun userTokenEnhancer(): TokenEnhancer {
    return UserTokenEnhancer()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...