I have a custom implementation of WebSecurityConfigurerAdapter where I override the config() method to authorize requests with matchers.
I need to create unit tests that use mock mvc to send requests to my controllers to make sure that they are being blocked properly. But when I run my tests, they don't load my implentation of WebSecurityConfigurerAdapter.
Overriden WebSecurityConfigurerAdapter::configure() method from my SecurityConfigSso.class:
@Override
protected void configure( HttpSecurity http ) throws Exception {
http.authorizeRequests()
.antMatchers( "/img/**", "lib/**", "/api/event**", "/api/event/**","/login/cas**" ).permitAll()
.antMatchers(HttpMethod.GET, "/**").hasAnyAuthority(AvailableRoles.ANY)
.antMatchers(HttpMethod.POST, "/**").hasAnyAuthority(AvailableRoles.ADMIN, AvailableRoles.GIS_ANALYST)
.antMatchers(HttpMethod.PUT, "/**").hasAnyAuthority(AvailableRoles.ADMIN, AvailableRoles.GIS_ANALYST)
.antMatchers(HttpMethod.DELETE, "/**").hasAnyAuthority(AvailableRoles.ADMIN, AvailableRoles.GIS_ANALYST)
.anyRequest().authenticated();
}
Here is my unit test:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { SecurityConfigSso.class })
public class SecurityTestControllerTests {
private final String SECURITY_URL = "/security";
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Before
public void init() {
Assert.assertNotNull(context);
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void postMethodShouldBeForbiddenToGuest() throws Exception {
this.mockMvc.perform(post(SECURITY_URL).with(user("test").roles(AvailableRoles.GUEST)))
.andExpect(status().isForbidden()).andReturn();
}
}
The result of this test should be a 403 from the server, but it's still 200... :(
You need to add security to the mockMvc:
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity())
.build();
For an example, have a look at https://github.com/spring-projects/spring-security/blob/master/test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/SecurityRequestsTests.java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With