问题描述
im使用Spring Boot开发服务器。我已经安装了所有的spring安全性设置,但是为了进行测试,我想停用它,以便于测试。 我只是继续并在类中评论了@Configuration批注,最终所有3个即时消息都使用了我为弹簧安全性而构建的。
//@Configuration
//@EnableWebSecurity
//@EnableGlobalMethodSecurity(securedEnabled = true,jsr250Enabled = true,prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService service;
@Autowired
private LogRepository logs;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/rest/user/register").permitAll()
.antMatchers(HttpMethod.PUT,"/rest/user/login").permitAll()
.antMatchers(HttpMethod.DELETE,"/rest/user/logout").permitAll()
.antMatchers("/rest/").authenticated()
.anyRequest().permitAll().and()
.addFilterBefore(new LoginFilter("/rest/user/login",super.authenticationManagerBean(),service,logs),BasicAuthenticationFilter.class)
.addFilterBefore(new RegisterFilter("/rest/user/register",service),BasicAuthenticationFilter.class)
.addFilterBefore(new logoutFilter("/rest/user/logout",BasicAuthenticationFilter.class)
.addFilterBefore(new ValidationFilter(service),BasicAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(service).passwordEncoder(new SHA512PasswordEncoder());
}
class SHA512PasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return DigestUtils.sha512Hex(rawPassword.toString());
}
@Override
public boolean matches(CharSequence rawPassword,String encodedPassword) {
return DigestUtils.sha512Hex(rawPassword.toString()).equals(encodedPassword);
}
}
}
但是由于某种原因,当我这样做时,这会显示在spring控制台中:
==========================
CONDITION EVALUATION DELTA
==========================
Positive matches:
-----------------
ManagementWebSecurityAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter' (OnClassCondition)
- found 'session' scope (OnWebApplicationCondition)
- @ConditionalOnMissingBean (types: org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; SearchStrategy: all) did not find any beans (OnBeanCondition)
有没有办法我可以“关闭”弹簧安全性进行测试,然后将其重新激活以用于实时版本?
解决方法
有很多方法可以完成此任务,以下是几种方法:
-
通过在测试类中使用注释
-
。示例:
@EnableWebMvc @AutoConfigureMockMvc(addFilters = false) public class DummyControllerTest { //your tests }
-
在配置中使用配置文件,即:
i)将注释
@Profile(value = {"development","production"})
添加到WebSecurityConfigurerAdapter
的实现中,然后在test/resources
中创建application-test.yml
来定义测试配置文件的属性并添加security:basic:enabled: false
ii)将其添加到测试文件
@ActiveProfiles(value = "test")
@AutoConfigureMockMvc(addFilters = false)