【问题标题】:@WebMvcTest using security returns 401 status instead of redirection@WebMvcTest 使用安全返回 401 状态而不是重定向
【发布时间】: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


【解决方案1】:

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

我检查了MockMvc 在这种情况下做了什么。在FilterSecurityInterceptor 过滤期间,AccessDeniedException 被抛出,ExceptionTranslationFilterhandleSpringSecurityException 中处理它,并且确实将响应状态设置为 401。

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

【讨论】:

    猜你喜欢
    • 2013-09-10
    • 2015-11-11
    • 1970-01-01
    • 2019-03-23
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多