使用安全性的@WebMvcTest返回401状态而不是重定向

时间:2019-05-13 05:36:43

标签: spring-boot spring-security spring-test spring-test-mvc

我正在使用Spring Security为一个简单的控制器编写测试。启用了登录表单。当用户输入/books URL时,他们将被重定向到登录页面。这就是我在Web控制台中看到的。 GET上的/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);
    }
}

为什么我的测试不像下面的浏览器那样重定向? enter image description here

我尝试在测试中添加@Import(BasicSecurityConfiguration.class),但仍然得到401。

这是我正在使用的Spring Boot版本:springBootVersion = '2.1.0.M2'

1 个答案:

答案 0 :(得分:0)

我遇到了here的讨论,该讨论有关客户端尝试访问受保护资源时应返回什么状态。应该是客户端错误还是重定向。最令我信服的答案是服务器应返回401/403。

在这种情况下,我检查了$sql = "SELECT count(*),year.year_name FROM `student` INNER JOIN year on student.year = year.id where student.status = '1' GROUP BY student.year" ; return $this->db->query($sql)->result(); 的工作。在MockMvc中进行过滤期间,引发了FilterSecurityInterceptorAccessDeniedExceptionExceptionTranslationFilter中对其进行了处理,实际上将响应状态设置为401。

我正在修改测试以断言服务器返回4xx状态。

相关问题