![](/img/trans.png)
[英]SpringBoot @WebMvcTest, autowiring RestTemplateBuilder
[英]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.