如何在WebSecurity配置适配器中提供spring配置bean进行测试?

xggvc2p6  于 2021-09-30  发布在  Java
关注(0)|答案(1)|浏览(336)

我使用以下方法 SecurityConfiguration 用于保护spring引导应用程序中端点的类。这门课取决于 ApiConfiguration 类,该类为内存中身份验证提供用户名和密码。
当开始一个 @WebMvcTest 对于控制器,spring还尝试初始化安全配置,但无法加载应用程序上下文。

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ApiConfiguration' available: expected at least 1 bean which qualifies as autowire candidate.

我试着添加一个 MockBean 对于测试类:

@MockBean
private ApiConfiguration apiConfiguration;

这解决了上述问题,但用户名和密码为空。
为测试提供这个配置bean是否有任何spring支持?

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {

    @Configuration
    @Order(1)
    public static class ApiSecurityConfiguration extends WebSecurityConfigurerAdapter {

        private static final String API_USER_ROLE = "API_USER";

        private final ApiConfiguration apiConfig;

        public ApiSecurityConfiguration(ApiConfiguration apiConfig) {
            this.apiConfig = apiConfig;
        }

        @Bean
        PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser(apiConfig.getUsername())
                    .password(passwordEncoder().encode(apiConfig.getPassword()))
                    .roles(API_USER_ROLE);
        }

        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity
                    .csrf().disable()
                    .formLogin().disable()
                    .mvcMatcher("/api/**")
                    .authorizeRequests()
                    .anyRequest().hasRole(API_USER_ROLE)
                    .and()
                    .httpBasic()
                    .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    }
}
iovurdzv

iovurdzv1#

我最终创造了一个 CustomApiConfiguration 注有 @TestConfiguration . 这似乎奏效了。至少,spring能够在设置 SecurityConfiguration 班级。

@TestConfiguration
public class CustomApiConfiguration {

    @Bean
    public ApiConfiguration apiConfiguration() {
        final ApiConfiguration config = new ApiConfiguration();
        config.setUsername("api-username");
        config.setPassword("api-password");
        return config;
    }
}

相关问题