Environment : I have an application for microservice architecture with spring boot, consisting of several infrastructure services and resources (containing business logic). Authorization and authentication are handled by the oAuth2-Service, which manages user objects and the creation of JWT tokens for clients.
To test one microservice application as a whole, I tried to build tests using testNG, spring.boot.test, org.springframework.security.test ...
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = {"spring.cloud.discovery.enabled=false", "spring.cloud.config.enabled=false", "spring.profiles.active=test"}) @AutoConfigureMockMvc @Test public class ArtistControllerTest extends AbstractTestNGSpringContextTests { @Autowired private MockMvc mvc; @BeforeClass @Transactional public void setUp() { // nothing to do } @AfterClass @Transactional public void tearDown() { // nothing to do here } @Test @WithMockUser(authorities = {"READ", "WRITE"}) public void getAllTest() throws Exception { // EXPECT HTTP STATUS 200 // BUT GET 401 this.mvc.perform(get("/") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) } }
where the security configuration (resource server) is as follows
@Configuration @EnableResourceServer public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
and the next method-based security check annotated inside the controller class
@PreAuthorize("hasAuthority('READ')") @RequestMapping(value = "/", method = RequestMethod.GET) public List<Foo> getAll(Principal user) { List<Foo> foos = fooRepository.findAll(); return foos; }
I thought this would work, but when I run the test I get an assertion error
java.lang.AssertionError: Status Expected :200 Actual :401
Question : Is there something completely obvious that I'm doing wrong? Or is @WithMockUser not going to work with @SpringBootTest and @AutoConfigureMockMvc in oAuth2? If so ... what would be the best approach for testing security configurations based on routes and methods as part of such an (integration) test like this?
Appendix : I also tried different approaches like something like the following ... but this led to the same result :(
this.mvc.perform(get("/") .with(user("admin").roles("READ","WRITE").authorities(() -> "READ", () -> "WRITE")) .accept(MediaType.APPLICATION_JSON))
see :
spring security testing
spring download 1.4 for testing