Skip to content

OAuth2 request parameter binding not available in @WebMvcTest #19823

@dsyer

Description

@dsyer

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions