Here's a @Controller
mapping, like one in the Spring Security samples:
@Controller
class OAuth2LoginController {
@GetMapping("/")
public String index(Model model, @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
@AuthenticationPrincipal OAuth2User oauth2User) {
...
The handler method params cannot be bound in a @WebMvcTest
:
@WebMvcTest(OAuth2LoginController.class)
class DemoApplicationTests {
@Autowired
MockMvc mvc;
@Test
public void rootWhenAuthenticatedReturnsUserAndClient() throws Exception {
this.mvc.perform(get("/").with(oauth2Login()))
.andExpect(model().attribute("userName", "test-subject"))
.andExpect(model().attribute("clientName", "test"))
.andExpect(model().attribute("userAttributes", Collections.singletonMap("sub", "test-subject")));
}
}
unless you manually add 2 beans that in the app (not in the test) are added via autoconfiguration:
@MockBean
ClientRegistrationRepository clientRegistrationRepository;
@TestConfiguration
static class AuthorizedClient {
@Bean
public OAuth2AuthorizedClientRepository authorizedClientRepository() {
return new HttpSessionOAuth2AuthorizedClientRepository();
}
}
Seems like maybe spring-boot-test-autoconfigure
is missing something in spring.factories
?
There's a sample app here: https://github.com/spring-projects/spring-security/blob/master/samples/boot/oauth2login/src/test/java/sample/web/OAuth2LoginControllerTests.java
Comment From: snicoll
Some interesting context from the Spring Security team:
OAuth2AuthorizedClientArgumentResolver is not being registered by OAuth2ClientConfiguration. This is automatically registered when using Spring MVC and both ClientRegistrationRepository and OAuth2AuthorizedClientRepository are registered.
Comment From: mbhave
Makes sense to me. I think we need to add OAuth2ClientAutoConfiguration
(and the reactive equivalent) to spring.factories
. Wonder if we should also do this for OAuth2ResourceServerAutoConfiguration
.