簡體   English   中英

SpringBoot @WebMvcTest安全問題

[英]SpringBoot @WebMvcTest security issue

我有一個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

當我打印請求響應時,我發現它因為安全性而抱怨。 “錯誤消息=訪問此資源需要完全身份驗證”任何想法,為什么它不使用我的安全配置,以及強制它使用正確配置的工作是什么? 提前致謝

終於找到了原因。 由於WebMvcTest只是切片測試,因此不需要安全配置。 解決方法是明確導入它,如,

@Import(WebSecurityConfig.class)

我遇到了同樣的問題,經過一段時間的搜索后,我找到了以下解決方案。

因為您在應用程序中啟用了Spring Security以及其他注釋,所以可以在@AutoConfigureMockMvc注釋中指定secure=false參數,如下所示:

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

說明:要禁用Spring Security自動配置,我們可以使用MockMvc實例來禁用@AutoConfigureMockMvc(secure=false)@AutoConfigureMockMvc(secure=false)

這解決了我同樣的問題

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM