Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spring MockMVC with custom Spring Security WebSecurityConfigurerAdapter

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... :(

like image 543
brandon d tran Avatar asked Feb 25 '17 01:02

brandon d tran


1 Answers

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

like image 62
Jeff E Avatar answered Oct 05 '22 22:10

Jeff E