问题
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
回答1:
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)
回答2:
I had the same issue and after searching for a while, I found the following solution.
Because, you have Spring Security enabled in your application, along with other annotations, you can specify the secure=false
parameter in @AutoConfigureMockMvc
annotation like this:
@AutoConfigureMockMvc(secure=false)
public class YourControllerTest {
//All your test methods here
}
Explanation:
To disable the Spring Security auto-configuration, we can use the MockMvc
instance to disable security with @AutoConfigureMockMvc(secure=false)
回答3:
This solved me the same issue
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ClientResourceControllerTest {
来源:https://stackoverflow.com/questions/45116833/springboot-webmvctest-security-issue