SpringBoot @WebMvcTest 安全问题

问题描述 投票:0回答:4

我有一个 Spring Rest MVC 控制器,其 url 为“/public/rest/vehicle/get”。在我的安全配置中,我定义了对 /public/rest 的任何请求都不需要身份验证。

    http.
             csrf().disable()
            .authorizeRequests()
            .antMatchers("/home/**", "/**", "/css/**", "/js/**", "/fonts/**", "/images/**", "/public/rest/**","/login*","/signin/**","/signup/**").permitAll()
            .antMatchers("/property/**").authenticated()
            .and()
            .formLogin().loginPage("/login").permitAll()
            .and().httpBasic().disable();

当我启动应用程序并使用浏览器或任何其他方式提交请求时,此配置工作正常。 现在,我有一个如下所示的测试类,

@RunWith(SpringRunner.class)
@WebMvcTest(VehicleController.class)
public class VehicleControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private VehicleService vehicleService;


    @Test
    public void getVehicle() throws Exception {
       given(this.vehicleService.get(0)).
               willReturn(new VehicleEquipmentDTO());
        this.mockMvc.perform(get("/public/rest/vehicle/get").param("id","0"))
                .andDo(print())
                .andExpect(status().isOk());//.andExpect(content().string("Honda Civic"));
    }}

现在,当我运行此测试时,它说

java.lang.AssertionError: Status 
Expected :200
Actual   :401

当我打印请求响应时,我看到它因安全原因而抱怨。 “错误消息=需要完全身份验证才能访问此资源” 任何想法为什么它不能使用我拥有的安全配置,以及强制它使用正确配置的解决方法是什么?预先感谢

java spring rest mockmvc
4个回答
22
投票

终于找到原因了。由于WebMvcTest只是切片测试,因此不会进行安全配置。解决方法是显式导入它,

@Import(WebSecurityConfig.class)

6
投票

我也遇到了同样的问题,经过一段时间的搜索,我找到了以下解决方案。

因为您在应用程序中启用了 Spring Security 以及其他注释,所以您可以在

secure=false
注释中指定
@AutoConfigureMockMvc
参数,如下所示:

@AutoConfigureMockMvc(secure=false)
public class YourControllerTest {
//All your test methods here
}

说明: 要禁用 Spring Security 自动配置,我们可以使用

MockMvc
实例通过
@AutoConfigureMockMvc(secure=false)

禁用安全性

5
投票

这解决了我同样的问题

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ClientResourceControllerTest {

0
投票

这对我的 Spring Boot 3 有用。只需禁用过滤器即可。

@AutoConfigureMockMvc(addFilters = false)
© www.soinside.com 2019 - 2024. All rights reserved.