I am using spring-security for OAuth2 Authentication and Authorization, here is a similar filter chain example
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(
authorize - >
authorize
.requestMatchers("/api/**")
.authenticated())
.oauth2ResourceServer(resourceServer -> resourceServer.jwt(withDefaults()))
.oauth2Login(withDefaults());
return http.build();
}
In all my tests i have been including with(oauth2Login())
, example:
public class HelloControllerTests {
@Autowired private MockMvc mockMvc;
@Test
public void shouldReturnWorld() throws Exception {
this.mockMvc
.perform(get("/api/hello").with(oauth2Login()))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Hello, World!")));
}
@Test
public void shouldReturnBob() throws Exception {
this.mockMvc
.perform(get("/api/hello").with(oauth2Login()).param("name", "bob"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Hello, Bob")));
}
}
I would like to know if it would be possible to mark the test with e.g @EnsureAuthenticatied
or parametize the mockMvc
such as it will run the test twice:
- Once authenticated, running the expectations that i write
- Once not authenticated, expecting just status 403 and a common error message