Spring Boot - 在启动时覆盖OAuth客户端配置

时间:2017-07-18 13:12:02

标签: spring spring-boot oauth openid

我有一个带有以下配置的Spring Boot应用程序:

@SpringBootApplication
@EnableOAuth2Sso
@Configuration
public class DemoApplication extends WebSecurityConfigurerAdapter {

 @Override
    public void configure(HttpSecurity http) throws Exception {

        http
            .antMatcher("/**")
            .authorizeRequests()
            .antMatchers("/","/appConfig", "/login/**", "/webjars/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
            .and().logout()
            .logoutSuccessUrl("/").permitAll()
            .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

    } 
...
}

在资源中,我有一个application.yml,它包含客户端配置:

security:
      oauth2:
        client:
          clientId: @keycloak.client.id@
          clientSecret: @keycloak.client.secret@
          accessTokenUri: https://@keycloak.host@:@keycloak.port@/auth/realms/@keycloak.realm@/protocol/openid-connect/token
          userAuthorizationUri: https://@keycloak.host@:@keycloak.port@/auth/realms/@keycloak.realm@/protocol/openid-connect/auth
          authenticationScheme: header
          clientAuthenticationScheme: header
        resource:
          userInfoUri: https://@keycloak.host@:@keycloak.port@/auth/realms/@keycloak.realm@/protocol/openid-connect/userinfo

到目前为止它工作正常,但我必须在应用程序启动时以编程方式设置clientSecret(也许还有其他属性),因为客户端在启动时也在OpenId服务器上注册,所以秘密只有在注册完成。

我使用AuthorizationServerConfigurerAdapter进行了一些实验来创建一个inMemory客户端,但是如果它也被添加到过滤器链中,那么应用程序根本不会启动:

- Bean method 'userInfoRestTemplateFactory' not loaded because @ConditionalOnMissingBean (types: org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration; SearchStrategy: all) found bean 'org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration'

如何在启动时从代码中设置clientSecret,而不是在application.yml中对其进行硬编码?

1 个答案:

答案 0 :(得分:0)

这些属性转到ResourceServerProperties对象。如果你自己创建它会怎么样:

@Bean
public ResourceServerProperties ouathResource() {
   // read from somewhere
   return new ResourceServerProperties( id, secret)
}

此bean的存在可能会抑制其他bean的自动创建,在这种情况下,它们也必须手动创建。