SpringBoot @WebMvcTest 安全问题 [英] SpringBoot @WebMvcTest security issue
问题描述
我有一个 spring rest mvc 控制器,其 URL 为/public/rest/vehicle/get".在我的安全配置中,我定义了对/public/rest 的任何请求都不需要身份验证.
I have a spring rest mvc controller which has the url "/public/rest/vehicle/get". In my security configuration, I have defined that any requests for /public/rest should not require authentication.
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();
当我启动我的应用程序并使用浏览器或任何其他方式提交请求时,此配置工作正常.现在,我有一个看起来像这样的测试类,
This configuration works fine when I start my application and submit request using browser or any other mean. Now, I have a test class which looks like this,
@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"));
}}
现在,当我运行这个测试时,它说
Now, when I run this test, it says
java.lang.AssertionError: Status
Expected :200
Actual :401
当我打印请求响应时,我看到它因为安全而抱怨.错误消息 = 访问此资源需要完全身份验证"任何想法为什么它不能使用我拥有的安全配置,以及强制它使用正确配置的解决方法是什么?提前致谢
When I print the request response, I see it is complaining because of security. "Error message = Full authentication is required to access this resource" Any ideas why it is not working with the security config that I have, and what is the work around to force it to use the correct configurations? Thanks in advance
推荐答案
终于找到原因了.由于 WebMvcTest 只是切片测试,因此不会进行安全配置.解决方法是显式导入它,
Finally found the reason. Since WebMvcTest is only sliced testing, it would not take the security configurations. The work around is to explicitly import it like,
@Import(WebSecurityConfig.class)
这篇关于SpringBoot @WebMvcTest 安全问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!