【发布时间】:2019-09-30 01:20:15
【问题描述】:
我正在使用 Spring Security 为一个简单的控制器编写测试。启用了登录表单。当用户输入/books URL 时,他们将被重定向到登录页面。这就是我在 Web 控制台中看到的。 GET on /books 返回 302,然后是 /login 和状态 200。
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = BookController.class)
public class BookControllerIT {
@Autowired
private MockMvc mockMvc;
// ... some mock beans
@Test
public void shouldReturnUnauthorizedStatus() throws Exception {
mockMvc.perform(get("/books")).andExpect(status().is3xxRedirection());
}
}
这是我的安全配置:
@Configuration
@EnableWebSecurity
public class BasicSecurityConfiguration extends WebSecurityConfigurerAdapter {
private DataSource dataSource;
private BCryptPasswordEncoder encoder;
@Autowired
public BasicSecurityConfiguration(@Qualifier("security.datasource") DataSource dataSource, BCryptPasswordEncoder encoder) {
this.dataSource = dataSource;
this.encoder = encoder;
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/").permitAll()
.and()
.authorizeRequests().antMatchers("/h2-console/**").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.and()
.httpBasic()
.and()
.csrf().disable()
.headers().frameOptions().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(encoder);
}
}
我尝试在测试中添加 @Import(BasicSecurityConfiguration.class),但仍然得到 401。
这是我正在使用的 Spring Boot 版本:springBootVersion = '2.1.0.M2'
【问题讨论】:
-
这是您的测试安全配置吗?
-
这是主包中的配置。
-
你使用的是什么版本的 Spring Boot?
-
我使用的是 2.1.0.M2
-
如果将@WebMvcTest 替换为@SpringBootTest 是否可以正常工作?
标签: spring-boot spring-security spring-test spring-test-mvc