0
votes

Is there a way to describe the same oauth2 configuration as below but via Java Class? And is it possible to reload it on the fly? I have taken this configuration from the official manual: https://spring.io/blog/2019/08/16/securing-services-with-spring-cloud-gateway

security:
    oauth2:
      client:
        registration:
          gateway:
            provider: uaa
            client-id: gateway
            client-secret: secret
            authorization-grant-type: authorization_code
            redirect-uri-template: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope: openid,profile,email,resource.read
        provider:
          uaa:
            authorization-uri: http://localhost:8090/uaa/oauth/authorize
            token-uri: http://uaa:8090/uaa/oauth/token
            user-info-uri: http://uaa:8090/uaa/userinfo
            user-name-attribute: sub
            jwk-set-uri: http://uaa:8090/uaa/token_keys
1

1 Answers

0
votes

You can override the Spring Boot auto-configuration, by registering a ClientRegistrationRepository bean:

@Bean
public ReactiveClientRegistrationRepository clientRegistrations() {
    ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("gateway")
        .clientId("gateway")
        .clientSecret("secret")
        .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
        .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}")
        .scope("openid", "profile", "email", "resource.read")
        .authorizationUri("http://localhost:8090/uaa/oauth/authorize")
        .tokenUri("http://uaa:8090/uaa/oauth/token")
        .userInfoUri("http://uaa:8090/uaa/userinfo")
        .userNameAttributeName(IdTokenClaimNames.SUB)
        .jwkSetUri("http://uaa:8090/uaa/token_keys")
        .build();
    return new InMemoryReactiveClientRegistrationRepository(clientRegistration);
}

and providing a WebSecurityConfigurerAdapter (or a SecurityFilterChain if you're using Spring Security 5.4 or later) that enables OAuth 2.0 Login through httpSecurity.oauth2Login():

@EnableWebSecurity
public class UiSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2Login(withDefaults());
    }
}

You an find more information in the Spring Security reference documentation.