Search code examples
javaspring-bootspring-securityoauth-2.0spring-security-oauth2

How to set any attribute in ClientRegistration in spring oauth2


Since I cannot keep client secret in application.yml , so it's kept in vault and from there it gets resolved. However, I can see that ClientRegistration is a final class , hence it's client secret can't be set later once the bean is already initialized.

In such case how can I set secret & use new object of ClientRegistration in all the referred beans.

Something like below I am trying to achieve but don't how to set enrichedClientRegistration in webclient or other referred places.

@Slf4j
@Configuration
public class WebClientConfig {

    @Bean
    WebClient authWebClient(ClientRegistrationRepository clientRegistrations,
                                    OAuth2AuthorizedClientRepository authorizedClients,
                                    PasswordResolver passwordResolver) {
        var clientRegistration = clientRegistrations.findByRegistrationId("myApp");
        log.info("Before client secret is {}",clientRegistration.getClientSecret());
        var clientSecret = passwordResolver.resolve(clientRegistration.getClientSecret());
        log.info("Resolved client secret is {}", clientSecret);
        var enrichedClientRegistration=ClientRegistration.withClientRegistration(clientRegistration)
                .clientSecret(clientSecret)
                .build();
        log.info("After client secret is {}",clientRegistrations.findByRegistrationId("myApp").getClientSecret());
        var oauth = new ServletOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients);
        oauth.setDefaultClientRegistrationId("myApp");

        return WebClient.builder()
                .apply(oauth.oauth2Configuration())
                .build();
    }
}

Solution

  • Since ClientRegistration is a final class which in injected into ClientRegistrationRepository, so you need completely override ClientRegistrationRepository as per example given in spring documentation.

    https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/jc.html#jc-oauth2login-completely-override-autoconfiguration