I am using spring security 4.x @WithSecurityContext('user') annotation to create a mock SecurityContext with 'user' logged in. Then, when calling my REST API using MockMvc I retrieve the SecurityContext and attach it to the call,
Like this:
@Test @Transactional @WithSecurityContext('user') public void getAllParcels() throws Exception {
where security() is the static method:
public static RequestPostProcessor security() { return SecurityMockMvcRequestPostProcessors.securityContext(SecurityContextHolder.getContext()); }
Thus, for my testing method, @WithSecurityContext('user') mock SecurityContext with an authenticated user with the username 'user' . Then in this method, I extract this SecurityContext layout and attach it to the REST API call to make my oAuth think the user is fully authenticated. This is basically the first approach you suggested in your question.
For this to work, you must switch your OAuth to a state sufficient for tests. Otherwise it will not work.
those. like this:
@Configuration public class OAuth2ServerConfiguration { @Configuration @EnableResourceServer protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Autowired(required = false) @Qualifier("oauth2StatelessSecurityContext") private Boolean stateless = Boolean.TRUE;
You see my stateless property, which is introduced only in the test. In normal mode, it uses the default value of true (therefore, it has no state). For tests, I declare an oauth2StatelessSecurityContext Bean with false to make it statefull for tests.
I define this configuration for tests:
@Configuration public class OAuth2Statefull { @Bean @Primary public Boolean oauth2StatelessSecurityContext() { return Boolean.FALSE; } }
How i did it. I hope my explanation is clear.