有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java SpringBoot@WebMvcTest安全问题

我有一个SpringRESTMVC控制器,其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

当我打印请求响应时,我看到它因为安全问题而抱怨“错误消息=访问此资源需要完全身份验证” 你知道为什么它不能使用我的安全配置吗?强迫它使用正确配置的方法是什么?提前谢谢


共 (3) 个答案

  1. # 1 楼答案

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

    因为在应用程序中启用了Spring安全性以及其他注释,所以可以在@AutoConfigureMockMvc注释中指定secure=false参数,如下所示:

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

    说明: 要禁用Spring安全自动配置,我们可以使用MockMvc实例禁用@AutoConfigureMockMvc(secure=false)的安全性

  2. # 2 楼答案

    终于找到了原因。由于WebMvcTest只是分片测试,因此不需要安全配置。解决方法是显式地导入它

    @Import(WebSecurityConfig.class)
    
  3. # 3 楼答案

    这解决了我同样的问题

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