Search in sources :

Example 76 with OAuth2AuthorizedClient

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

the class ClientCredentialsOAuth2AuthorizedClientProvider method authorize.

/**
 * Attempt to authorize (or re-authorize) the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
 * {@code context}. Returns {@code null} if authorization (or re-authorization) is not
 * supported, e.g. the client's {@link ClientRegistration#getAuthorizationGrantType()
 * authorization grant type} is not {@link AuthorizationGrantType#CLIENT_CREDENTIALS
 * client_credentials} OR the {@link OAuth2AuthorizedClient#getAccessToken() access
 * token} is not expired.
 * @param context the context that holds authorization-specific state for the client
 * @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization (or
 * re-authorization) is not supported
 */
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
    Assert.notNull(context, "context cannot be null");
    ClientRegistration clientRegistration = context.getClientRegistration();
    if (!AuthorizationGrantType.CLIENT_CREDENTIALS.equals(clientRegistration.getAuthorizationGrantType())) {
        return null;
    }
    OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
    if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
        // need for re-authorization
        return null;
    }
    // As per spec, in section 4.4.3 Access Token Response
    // https://tools.ietf.org/html/rfc6749#section-4.4.3
    // A refresh token SHOULD NOT be included.
    // 
    // Therefore, renewing an expired access token (re-authorization)
    // is the same as acquiring a new access token (authorization).
    OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
    OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, clientCredentialsGrantRequest);
    return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest) Nullable(org.springframework.lang.Nullable)

Example 77 with OAuth2AuthorizedClient

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

the class AuthenticatedPrincipalOAuth2AuthorizedClientRepositoryTests method saveAuthorizedClientWhenAuthenticatedPrincipalThenSaveToService.

@Test
public void saveAuthorizedClientWhenAuthenticatedPrincipalThenSaveToService() {
    Authentication authentication = this.createAuthenticatedPrincipal();
    OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
    this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authentication, this.request, this.response);
    verify(this.authorizedClientService).saveAuthorizedClient(authorizedClient, authentication);
}
Also used : Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Example 78 with OAuth2AuthorizedClient

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

the class DefaultOAuth2AuthorizedClientManagerTests method authorizeWhenAuthorizedAndSupportedProviderThenReauthorized.

@SuppressWarnings("unchecked")
@Test
public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() {
    given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))).willReturn(this.clientRegistration);
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()), eq(this.principal), eq(this.request))).willReturn(this.authorizedClient);
    OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
    given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(reauthorizedClient);
    // @formatter:off
    OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal).attributes((attrs) -> {
        attrs.put(HttpServletRequest.class.getName(), this.request);
        attrs.put(HttpServletResponse.class.getName(), this.response);
    }).build();
    // @formatter:on
    OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
    verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
    verify(this.contextAttributesMapper).apply(any());
    OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
    assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
    assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
    assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
    assertThat(authorizedClient).isSameAs(reauthorizedClient);
    verify(this.authorizationSuccessHandler).onAuthorizationSuccess(eq(reauthorizedClient), eq(this.principal), any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal), eq(this.request), eq(this.response));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) OAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) ArgumentCaptor(org.mockito.ArgumentCaptor) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Authentication(org.springframework.security.core.Authentication) TestOAuth2RefreshTokens(org.springframework.security.oauth2.core.TestOAuth2RefreshTokens) ClientAuthorizationException(org.springframework.security.oauth2.client.ClientAuthorizationException) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) StringUtils(org.springframework.util.StringUtils) Mockito.mock(org.mockito.Mockito.mock) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Example 79 with OAuth2AuthorizedClient

use of org.springframework.security.oauth2.client.OAuth2AuthorizedClient 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 80 with OAuth2AuthorizedClient

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

the class DefaultOAuth2AuthorizedClientManagerTests method authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized.

@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() {
    given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))).willReturn(this.clientRegistration);
    given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(this.authorizedClient);
    // @formatter:off
    OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal).attributes((attrs) -> {
        attrs.put(HttpServletRequest.class.getName(), this.request);
        attrs.put(HttpServletResponse.class.getName(), this.response);
    }).build();
    // @formatter:on
    OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
    verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
    verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
    OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
    assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
    assertThat(authorizationContext.getAuthorizedClient()).isNull();
    assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
    assertThat(authorizedClient).isSameAs(this.authorizedClient);
    verify(this.authorizationSuccessHandler).onAuthorizationSuccess(eq(this.authorizedClient), eq(this.principal), any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(eq(this.authorizedClient), eq(this.principal), eq(this.request), eq(this.response));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) OAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) ArgumentCaptor(org.mockito.ArgumentCaptor) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Authentication(org.springframework.security.core.Authentication) TestOAuth2RefreshTokens(org.springframework.security.oauth2.core.TestOAuth2RefreshTokens) ClientAuthorizationException(org.springframework.security.oauth2.client.ClientAuthorizationException) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) StringUtils(org.springframework.util.StringUtils) Mockito.mock(org.mockito.Mockito.mock) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)140 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)123 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)66 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)51 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)45 Instant (java.time.Instant)43 Authentication (org.springframework.security.core.Authentication)41 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)36 ClientRequest (org.springframework.web.reactive.function.client.ClientRequest)34 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)32 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)31 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)31 BeforeEach (org.junit.jupiter.api.BeforeEach)28 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)23 Map (java.util.Map)21 HashMap (java.util.HashMap)20 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)19 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)17 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)17 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)17