Spring Security 为Spring授权服务器自动连接特定的密码编码器

qv7cva1a  于 2023-03-02  发布在  Spring
关注(0)|答案(1)|浏览(214)

我的应用有两个PasswordEncoder bean,并希望使用spring-security-oauth2-authorization-server。

implementation("org.springframework.security:spring-security-oauth2-authorization-server:1.0.0")
  • 两个密码编码器Bean
@Bean("v1-encoder")
    fun v1Encoder(): PasswordEncoder {
        return V1PasswordEncoder()
    }

    @Bean("v0-encoder")
    fun v0Encoder(): PasswordEncoder {
        return V0PasswordEncoder()
    }
  • 所以Spring授权服务器抱怨多个bean:
Parameter 0 of method setFilterChains in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a single bean, but 2 were found:
  • www.example.com上的代码失败https://github.com/spring-projects/spring-authorization-server/blob/1.0.0/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientAuthenticationConfigurer.java#L231
PasswordEncoder passwordEncoder = OAuth2ConfigurerUtils.getOptionalBean(httpSecurity, PasswordEncoder.class);

如何为OAuth2ServerSecurityConfig自动连接v1-encoder,以便它能够找到v1-encoder bean?

  • 我的简单Spring身份验证服务器配置
@Configuration
class OAuth2ServerSecurityConfig {

   @Bean
   @Order(1)
   fun authorizationServerSecurityFilterChain(http: HttpSecurity): SecurityFilterChain {
      OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http)
      http.getConfigurer(OAuth2AuthorizationServerConfigurer::class.java)
         .oidc(Customizer.withDefaults())
      return http.build()
   }

   @Bean
   fun authorizationServerSettings(): AuthorizationServerSettings {
      return AuthorizationServerSettings.builder().build()
   }

   @Bean
   fun registeredClientRepository(): RegisteredClientRepository {
      val registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
         .clientId("client")
         .clientSecret("{bcrypt}secret")
         .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
         .build()

      return InMemoryRegisteredClientRepository(registeredClient)
   }
qlckcl4x

qlckcl4x1#

不幸的是,框架严格要求0或1个bean存在。如果你能解释你的用例,可能会有其他的解决方案。一个选项(变通方案)是将你的第二个PasswordEncoder Package 在另一个组件中,例如:

@Bean
public PasswordEncoderHolder passwordEncoderHolder() {
    return new PasswordEncoderHolder();
}

public static final class PasswordEncoderHolder {
    private final PasswordEncoder passwordEncoder = new V0PasswordEncoder();

    public PasswordEncoder getInstance() {
        return this.passwordEncoder;
    }
}

那么,您只需要一个@Bean来实现v1-encoder

相关问题