Search in sources :

Example 1 with DefaultOAuth2AuthorizedClientManager

use of org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager in project spring-security by spring-projects.

the class OAuth2AuthorizedClientArgumentResolverTests method setup.

@BeforeEach
public void setup() {
    this.authentication = new TestingAuthenticationToken(this.principalName, "password");
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(this.authentication);
    SecurityContextHolder.setContext(securityContext);
    // @formatter:off
    this.registration1 = ClientRegistration.withRegistrationId("client1").clientId("client-1").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/login/oauth2/code/{registrationId}").scope("user").authorizationUri("https://provider.com/oauth2/authorize").tokenUri("https://provider.com/oauth2/token").userInfoUri("https://provider.com/oauth2/user").userNameAttributeName("id").clientName("client-1").build();
    this.registration2 = ClientRegistration.withRegistrationId("client2").clientId("client-2").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).scope("read", "write").tokenUri("https://provider.com/oauth2/token").build();
    this.registration3 = TestClientRegistrations.password().registrationId("client3").build();
    // @formatter:on
    this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1, this.registration2, this.registration3);
    this.authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().authorizationCode().refreshToken().clientCredentials().build();
    DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
    this.authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName, mock(OAuth2AccessToken.class));
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration1.getRegistrationId()), any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient1);
    this.authorizedClient2 = new OAuth2AuthorizedClient(this.registration2, this.principalName, mock(OAuth2AccessToken.class));
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration2.getRegistrationId()), any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient2);
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Authentication(org.springframework.security.core.Authentication) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) SecurityContext(org.springframework.security.core.context.SecurityContext) InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) PasswordOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.PasswordOAuth2AuthorizedClientProvider) ClientCredentialsOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 2 with DefaultOAuth2AuthorizedClientManager

use of org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager in project spring-security by spring-projects.

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenRefreshRequiredThenRefreshAndResponseDoesNotContainRefreshToken.

@Test
public void filterWhenRefreshRequiredThenRefreshAndResponseDoesNotContainRefreshToken() {
    OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).build();
    RestOperations refreshTokenClient = mock(RestOperations.class);
    given(refreshTokenClient.exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class))).willReturn(new ResponseEntity(response, HttpStatus.OK));
    DefaultRefreshTokenTokenResponseClient refreshTokenTokenResponseClient = new DefaultRefreshTokenTokenResponseClient();
    refreshTokenTokenResponseClient.setRestOperations(refreshTokenClient);
    RefreshTokenOAuth2AuthorizedClientProvider authorizedClientProvider = new RefreshTokenOAuth2AuthorizedClientProvider();
    authorizedClientProvider.setAccessTokenResponseClient(refreshTokenTokenResponseClient);
    DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    this.function = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
    this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(), issuedAt, accessTokenExpiresAt);
    OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken);
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(new MockHttpServletRequest())).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(new MockHttpServletResponse())).build();
    this.function.filter(request, this.exchange).block();
    verify(refreshTokenClient).exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class));
    verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(), eq(this.authentication), any(), any());
    OAuth2AuthorizedClient newAuthorizedClient = this.authorizedClientCaptor.getValue();
    assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
    assertThat(newAuthorizedClient.getRefreshToken().getTokenValue()).isEqualTo(refreshToken.getTokenValue());
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    ClientRequest request0 = requests.get(0);
    assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-1");
    assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
    assertThat(request0.method()).isEqualTo(HttpMethod.GET);
    assertThat(getBody(request0)).isEmpty();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Instant(java.time.Instant) DefaultRefreshTokenTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultRefreshTokenTokenResponseClient) ResponseEntity(org.springframework.http.ResponseEntity) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) RestOperations(org.springframework.web.client.RestOperations) RequestEntity(org.springframework.http.RequestEntity) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) RefreshTokenOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 3 with DefaultOAuth2AuthorizedClientManager

use of org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager in project spring-security by spring-projects.

the class DefaultOAuth2AuthorizedClientManagerTests method setup.

@SuppressWarnings("unchecked")
@BeforeEach
public void setup() {
    this.clientRegistrationRepository = mock(ClientRegistrationRepository.class);
    this.authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    this.authorizedClientProvider = mock(OAuth2AuthorizedClientProvider.class);
    this.contextAttributesMapper = mock(Function.class);
    this.authorizationSuccessHandler = spy(new OAuth2AuthorizationSuccessHandler() {

        @Override
        public void onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Authentication principal, Map<String, Object> attributes) {
            DefaultOAuth2AuthorizedClientManagerTests.this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, (HttpServletRequest) attributes.get(HttpServletRequest.class.getName()), (HttpServletResponse) attributes.get(HttpServletResponse.class.getName()));
        }
    });
    this.authorizationFailureHandler = spy(new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler((clientRegistrationId, principal, attributes) -> this.authorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal, (HttpServletRequest) attributes.get(HttpServletRequest.class.getName()), (HttpServletResponse) attributes.get(HttpServletResponse.class.getName()))));
    this.authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider);
    this.authorizedClientManager.setContextAttributesMapper(this.contextAttributesMapper);
    this.authorizedClientManager.setAuthorizationSuccessHandler(this.authorizationSuccessHandler);
    this.authorizedClientManager.setAuthorizationFailureHandler(this.authorizationFailureHandler);
    this.clientRegistration = TestClientRegistrations.clientRegistration().build();
    this.principal = new TestingAuthenticationToken("principal", "password");
    this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.scopes("read", "write"), TestOAuth2RefreshTokens.refreshToken());
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
    this.authorizationContextCaptor = ArgumentCaptor.forClass(OAuth2AuthorizationContext.class);
}
Also used : OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Function(java.util.function.Function) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) HashMap(java.util.HashMap) Map(java.util.Map) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 4 with DefaultOAuth2AuthorizedClientManager

use of org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager in project spring-security by spring-projects.

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method setup.

@BeforeEach
public void setup() {
    this.authentication = new TestingAuthenticationToken("test", "this");
    JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider();
    jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(this.jwtBearerTokenResponseClient);
    // @formatter:off
    OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().authorizationCode().refreshToken((configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient)).clientCredentials((configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient)).password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient)).provider(jwtBearerAuthorizedClientProvider).build();
    // @formatter:on
    this.authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    this.authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    this.function = new ServletOAuth2AuthorizedClientExchangeFilterFunction(this.authorizedClientManager);
}
Also used : CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) BeforeEach(org.junit.jupiter.api.BeforeEach) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) OAuth2RefreshTokenGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest) RequestContextHolder(org.springframework.web.context.request.RequestContextHolder) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) DefaultClientCredentialsTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultClientCredentialsTokenResponseClient) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) Duration(java.time.Duration) Map(java.util.Map) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) Context(reactor.util.context.Context) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuth2PasswordGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) MockClientHttpRequest(org.springframework.mock.http.client.reactive.MockClientHttpRequest) Mockito.mock(org.mockito.Mockito.mock) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Mock(org.mockito.Mock) DefaultRefreshTokenTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultRefreshTokenTokenResponseClient) JwtBearerOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.JwtBearerOAuth2AuthorizedClientProvider) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ArrayList(java.util.ArrayList) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) RequestEntity(org.springframework.http.RequestEntity) OAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler) HttpMethod(org.springframework.http.HttpMethod) Mono(reactor.core.publisher.Mono) RestOperations(org.springframework.web.client.RestOperations) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) HttpStatus(org.springframework.http.HttpStatus) AfterEach(org.junit.jupiter.api.AfterEach) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) Mockito.never(org.mockito.Mockito.never) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) WebClient(org.springframework.web.reactive.function.client.WebClient) BodyInserter(org.springframework.web.reactive.function.BodyInserter) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) ServerSentEventHttpMessageWriter(org.springframework.http.codec.ServerSentEventHttpMessageWriter) URI(java.net.URI) Jwt(org.springframework.security.oauth2.jwt.Jwt) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) HttpHeaders(org.springframework.http.HttpHeaders) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test) List(java.util.List) Optional(java.util.Optional) Authentication(org.springframework.security.core.Authentication) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest) ClientAuthorizationException(org.springframework.security.oauth2.client.ClientAuthorizationException) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) RefreshTokenOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) MultipartHttpMessageWriter(org.springframework.http.codec.multipart.MultipartHttpMessageWriter) ByteBufferEncoder(org.springframework.core.codec.ByteBufferEncoder) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) HashMap(java.util.HashMap) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) Captor(org.mockito.Captor) ArgumentCaptor(org.mockito.ArgumentCaptor) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) TestOAuth2AccessTokenResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses) OAuth2AuthorizedClientProviderBuilder(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) Assertions.entry(org.assertj.core.api.Assertions.entry) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Mockito.verify(org.mockito.Mockito.verify) Consumer(java.util.function.Consumer) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) ResponseEntity(org.springframework.http.ResponseEntity) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) StringUtils(org.springframework.util.StringUtils) JwtBearerOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.JwtBearerOAuth2AuthorizedClientProvider) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) JwtBearerOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.JwtBearerOAuth2AuthorizedClientProvider) RefreshTokenOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 5 with DefaultOAuth2AuthorizedClientManager

use of org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager in project spring-security by spring-projects.

the class OAuth2AuthorizedClientArgumentResolverTests method resolveArgumentWhenAuthorizedClientNotFoundForClientCredentialsClientThenResolvesFromTokenResponseClient.

@SuppressWarnings("unchecked")
@Test
public void resolveArgumentWhenAuthorizedClientNotFoundForClientCredentialsClientThenResolvesFromTokenResponseClient() throws Exception {
    OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
    ClientCredentialsOAuth2AuthorizedClientProvider clientCredentialsAuthorizedClientProvider = new ClientCredentialsOAuth2AuthorizedClientProvider();
    clientCredentialsAuthorizedClientProvider.setAccessTokenResponseClient(clientCredentialsTokenResponseClient);
    DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    authorizedClientManager.setAuthorizedClientProvider(clientCredentialsAuthorizedClientProvider);
    this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).build();
    given(clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class))).willReturn(null);
    MethodParameter methodParameter = this.getMethodParameter("clientCredentialsClient", OAuth2AuthorizedClient.class);
    OAuth2AuthorizedClient authorizedClient = (OAuth2AuthorizedClient) this.argumentResolver.resolveArgument(methodParameter, null, new ServletWebRequest(this.request, this.response), null);
    assertThat(authorizedClient).isNotNull();
    assertThat(authorizedClient.getClientRegistration()).isSameAs(this.registration2);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName);
    assertThat(authorizedClient.getAccessToken()).isSameAs(accessTokenResponse.getAccessToken());
    verify(this.authorizedClientRepository).saveAuthorizedClient(eq(authorizedClient), eq(this.authentication), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Also used : ClientCredentialsOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest) MethodParameter(org.springframework.core.MethodParameter) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)7 DefaultOAuth2AuthorizedClientManager (org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager)7 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)6 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)6 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)6 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)5 OAuth2AuthorizedClientProvider (org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider)5 HashMap (java.util.HashMap)4 Test (org.junit.jupiter.api.Test)4 Authentication (org.springframework.security.core.Authentication)4 ClientCredentialsOAuth2AuthorizedClientProvider (org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider)4 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)4 Map (java.util.Map)3 RefreshTokenOAuth2AuthorizedClientProvider (org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider)3 RegisteredOAuth2AuthorizedClient (org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient)3 OAuth2ClientCredentialsGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest)3 ClientRegistrationRepository (org.springframework.security.oauth2.client.registration.ClientRegistrationRepository)3 OAuth2AuthorizedClientRepository (org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository)3 Duration (java.time.Duration)2 Collections (java.util.Collections)2