oauth-2.0 Spring安全性:在Sping Boot 2.7.2中升级已弃用的WebSecurityConfigurerAdapter时出错

eulz3vhy  于 2022-10-31  发布在  Spring
关注(0)|答案(1)|浏览(565)

我正在尝试将Spring Boot 版本从2.1.7.RELEASE升级到2.7.2。版本更改后,我看到WebSecurityConfigurerAdapter已弃用。当前配置如下所示。

@EnableOAuth2Sso
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigure extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests()
        .antMatchers(HttpMethod.POST, "**/api/**").permitAll()
        .antMatchers(HttpMethod.GET, "**/api/**").permitAll()
        .anyRequest().authenticated().and()
        .csrf().disable()
        .sessionManagement().maximumSessions(-1).sessionRegistry(sessionRegistry());

        http.headers().frameOptions().sameOrigin();

       TransactionSynchronizationManager.setActualTransactionActive(true);
   }
}

按照这个迁移指南-Spring Security without the WebSecurityConfigurerAdapter,我修改了代码如下。

@EnableOAuth2Sso
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigure {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().antMatchers(HttpMethod.POST, "**/api/**").permitAll()
            .antMatchers(HttpMethod.GET, "**/api/**").permitAll().anyRequest().authenticated().and().csrf()
            .disable().sessionManagement().maximumSessions(-1).sessionRegistry(sessionRegistry());

        http.headers().frameOptions().sameOrigin();

        TransactionSynchronizationManager.setActualTransactionActive(true);
        return http.build();
    }
}

更改后,我在启动应用程序时收到此错误。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.

我正在使用spring security oauth2来启用SSO

<dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.0.0.RELEASE</version>
    </dependency>

我非常怀疑@EnableOAuth2Sso错误背后的原因。任何帮助都将不胜感激。

mrphzbgm

mrphzbgm1#

如例外所示,由于@EnableOAuth2Sso导入了OAuth2SsoDefaultConfiguration,它是WebSecurityConfigurerAdapter的扩展,所以可以使用dsl http.oauth2Login()代替@EnableOAuth2Sso

相关问题