I\'m struggling with testing access control on URLs protected by Spring Security.
The configuration looks like this:
http
.authorizeReque
You should not add the FilterChainProxy directly. Instead, you should apply SecurityMockMvcConfigurers.springSecurity()
as indicated by the reference. An example is included below:
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
The result of this is:
FilterChainProxy
is added as a Filter
to MockMvc
(as you did)TestSecurityContextHolderPostProcessor
is addedWhy is TestSecurityContextHolderPostProcessor
necessary? The reason is that we need to communicate the current user from the test method to the MockHttpServletRequest
that is created. This is necessary because Spring Security's SecurityContextRepositoryFilter
will override any value on SecurityContextHolder
to be the value found by the current SecurityContextRepository
(i.e. the SecurityContext
in HttpSession
).
Update
Remember anything that contains role in the method name automatically prefixes "ROLE_" to the string that was passed in.
Based on your comment, the problem is you need to either update your configuration to use hasRole instead of hasAuthority (since your annotation is using roles):
.authorizeRequests()
.antMatchers("/api/user/**", "/user").authenticated()
.antMatchers("/api/admin/**", "/templates/admin/**", "/admin/**").hasRole("ADMIN")
.anyRequest().permitAll();
Alternatively
You in Spring Security 4.0.2+ you can use:
@WithMockUser(authorities="ADMIN")
Okay, figured it out.
mockMvc.perform(get("/api/user/account")
.with(user("user")))
.andExpect(status().isOk());
It works now.