我使用以下方法 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);
}
}
}
1条答案
按热度按时间iovurdzv1#
我最终创造了一个
CustomApiConfiguration
注有@TestConfiguration
. 这似乎奏效了。至少,spring能够在设置SecurityConfiguration
班级。