无法在自定义 Spring Boot 启动器中使用 WebSecurityConfigurerAdapter

Vla*_*ich 6 java spring spring-security spring-boot

我正在尝试通过定义从WebSecurityConfigurerAdapter. 然而,当我用这个启动器启动我的应用程序时,我得到:

IllegalStateException: Found WebSecurityConfigurerAdapter as well as SecurityFilterChain.
Please select just one.
Run Code Online (Sandbox Code Playgroud)

我发现由于spring security 的这个问题,不可能再这样做了。spring的WebSecurityConfiguration中有一个断言:

WebSecurityConfiguration.java 的快照

我解决了这个问题,在启动器中添加了以下内容(根据问题):

@Bean
@Order(1) //Explanation for this below
open fun filterChain(http: HttpSecurity, jwtHelper: JwtHelper): SecurityFilterChain {
    return http.authorizeRequests()
           ...
               .addFilterBefore(JwtAuthenticationFilter(jwtHelper), UsernamePasswordAuthenticationFilter::class.java)
               .and().build()
}

@Bean
open fun authenticationProvider(ldapConfig: LdapConfig): ActiveDirectoryLdapAuthenticationProvider {
    return ActiveDirectoryLdapAuthenticationProvider(...)
}
Run Code Online (Sandbox Code Playgroud)

我添加是@Order(1)因为有两个securityFilterChains:我的(在上面的配置中定义)和另一个来自未知来源的。我想,后者是无法使用的原因WebSecurityConfigurerAdapter

主要问题是我找不到它来自哪里。


断点来自WebSecurityConfiguration...以防万一: WebSecurityConfiguration 的断点

我想,因此我@EnableGlobalMethodSecurity(prePostEnabled = true) 也无法使用。它说:

Cannot apply org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration$EnableGlobalAuthenticationAutowiredConfigurer
to already built object
Run Code Online (Sandbox Code Playgroud)

这是我的依赖项列表:

  1. 具有初学者使用的模型的模块(名称:my-ldap-security-model):
dependencies {
    compileOnly 'org.springframework.security:spring-security-core'
    compileOnly 'org.springframework:spring-web'
    compileOnly 'javax.servlet:javax.servlet-api'
    api 'jakarta.xml.bind:jakarta.xml.bind-api'
    api 'org.glassfish.jaxb:jaxb-runtime'
    api 'io.jsonwebtoken:jjwt'
}
Run Code Online (Sandbox Code Playgroud)
  1. 具有启动器使用的模型的模块(名称:my-ldap-security-spring-boot-starter):
dependencies {
    compile project(':my-ldap-security-model')
    compileOnly 'javax.servlet:javax.servlet-api'
    api 'org.springframework.security:spring-security-core'
    api 'org.springframework.security:spring-security-config'
    api 'org.springframework.security:spring-security-web'
    api 'org.springframework:spring-web'
    api 'org.springframework.security:spring-security-ldap'
}
Run Code Online (Sandbox Code Playgroud)
  1. 应用项目:
dependencies {
    implementation('org.springframework.boot:spring-boot-starter-web')
    implementation('com.demo.boot:my-ldap-security-spring-boot-starter:0.0.1')
}
Run Code Online (Sandbox Code Playgroud)

请帮我找出该过滤器的根源。

Vla*_*ich 4

最初,SecurityFilterChain如果有任何WebSecurityConfigurerAdapter. 但是,如果 spring security 自动配置的优先级高于您的WebSecurityConfigurerAdapter.

解决方案:我@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)在上面添加了自动配置类。不再有默认的安全过滤器链:)

关于@EnableGlobalMethodSecurity...这是关于缓存的。突然,它就固定了。