Search in sources :

Example 1 with OAuth2RefreshTokenGrantRequest

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

the class DefaultRefreshTokenTokenResponseClient method getTokenResponse.

@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest) {
    Assert.notNull(refreshTokenGrantRequest, "refreshTokenGrantRequest cannot be null");
    RequestEntity<?> request = this.requestEntityConverter.convert(refreshTokenGrantRequest);
    ResponseEntity<OAuth2AccessTokenResponse> response = getResponse(request);
    OAuth2AccessTokenResponse tokenResponse = response.getBody();
    if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes()) || tokenResponse.getRefreshToken() == null) {
        OAuth2AccessTokenResponse.Builder tokenResponseBuilder = OAuth2AccessTokenResponse.withResponse(tokenResponse);
        if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) {
            // As per spec, in Section 5.1 Successful Access Token Response
            // https://tools.ietf.org/html/rfc6749#section-5.1
            // If AccessTokenResponse.scope is empty, then default to the scope
            // originally requested by the client in the Token Request
            tokenResponseBuilder.scopes(refreshTokenGrantRequest.getAccessToken().getScopes());
        }
        if (tokenResponse.getRefreshToken() == null) {
            // Reuse existing refresh token
            tokenResponseBuilder.refreshToken(refreshTokenGrantRequest.getRefreshToken().getTokenValue());
        }
        tokenResponse = tokenResponseBuilder.build();
    }
    return tokenResponse;
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)

Example 2 with OAuth2RefreshTokenGrantRequest

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

the class RefreshTokenReactiveOAuth2AuthorizedClientProvider method authorize.

/**
 * Attempt to re-authorize the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
 * {@code context}. Returns an empty {@code Mono} if re-authorization is not
 * supported, e.g. the client is not authorized OR the
 * {@link OAuth2AuthorizedClient#getRefreshToken() refresh token} is not available for
 * the authorized client OR the {@link OAuth2AuthorizedClient#getAccessToken() access
 * token} is not expired.
 *
 * <p>
 * The following {@link OAuth2AuthorizationContext#getAttributes() context attributes}
 * are supported:
 * <ol>
 * <li>{@code "org.springframework.security.oauth2.client.REQUEST_SCOPE"} (optional) -
 * a {@code String[]} of scope(s) to be requested by the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client}</li>
 * </ol>
 * @param context the context that holds authorization-specific state for the client
 * @return the {@link OAuth2AuthorizedClient} or an empty {@code Mono} if
 * re-authorization is not supported
 */
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
    Assert.notNull(context, "context cannot be null");
    OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
    if (authorizedClient == null || authorizedClient.getRefreshToken() == null || !hasTokenExpired(authorizedClient.getAccessToken())) {
        return Mono.empty();
    }
    Object requestScope = context.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
    Set<String> scopes = Collections.emptySet();
    if (requestScope != null) {
        Assert.isInstanceOf(String[].class, requestScope, "The context attribute must be of type String[] '" + OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
        scopes = new HashSet<>(Arrays.asList((String[]) requestScope));
    }
    ClientRegistration clientRegistration = context.getClientRegistration();
    OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, authorizedClient.getAccessToken(), authorizedClient.getRefreshToken(), scopes);
    return Mono.just(refreshTokenGrantRequest).flatMap(this.accessTokenResponseClient::getTokenResponse).onErrorMap(OAuth2AuthorizationException.class, (e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(), e)).map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) Arrays(java.util.Arrays) WebClientReactiveRefreshTokenTokenResponseClient(org.springframework.security.oauth2.client.endpoint.WebClientReactiveRefreshTokenTokenResponseClient) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) Set(java.util.Set) Mono(reactor.core.publisher.Mono) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) Instant(java.time.Instant) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) HashSet(java.util.HashSet) OAuth2RefreshTokenGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest) Duration(java.time.Duration) Clock(java.time.Clock) Collections(java.util.Collections) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) OAuth2Token(org.springframework.security.oauth2.core.OAuth2Token) Assert(org.springframework.util.Assert) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2RefreshTokenGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest)

Example 3 with OAuth2RefreshTokenGrantRequest

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

the class RefreshTokenOAuth2AuthorizedClientProvider method authorize.

/**
 * Attempt to re-authorize the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
 * {@code context}. Returns {@code null} if re-authorization is not supported, e.g.
 * the client is not authorized OR the {@link OAuth2AuthorizedClient#getRefreshToken()
 * refresh token} is not available for the authorized client OR the
 * {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
 *
 * <p>
 * The following {@link OAuth2AuthorizationContext#getAttributes() context attributes}
 * are supported:
 * <ol>
 * <li>{@link OAuth2AuthorizationContext#REQUEST_SCOPE_ATTRIBUTE_NAME} (optional) - a
 * {@code String[]} of scope(s) to be requested by the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client}</li>
 * </ol>
 * @param context the context that holds authorization-specific state for the client
 * @return the {@link OAuth2AuthorizedClient} or {@code null} if re-authorization is
 * not supported
 */
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
    Assert.notNull(context, "context cannot be null");
    OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
    if (authorizedClient == null || authorizedClient.getRefreshToken() == null || !hasTokenExpired(authorizedClient.getAccessToken())) {
        return null;
    }
    Object requestScope = context.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
    Set<String> scopes = Collections.emptySet();
    if (requestScope != null) {
        Assert.isInstanceOf(String[].class, requestScope, "The context attribute must be of type String[] '" + OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
        scopes = new HashSet<>(Arrays.asList((String[]) requestScope));
    }
    OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(authorizedClient.getClientRegistration(), authorizedClient.getAccessToken(), authorizedClient.getRefreshToken(), scopes);
    OAuth2AccessTokenResponse tokenResponse = getTokenResponse(authorizedClient, refreshTokenGrantRequest);
    return new OAuth2AuthorizedClient(context.getAuthorizedClient().getClientRegistration(), context.getPrincipal().getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2RefreshTokenGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest) Nullable(org.springframework.lang.Nullable)

Example 4 with OAuth2RefreshTokenGrantRequest

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

the class WebClientReactiveRefreshTokenTokenResponseClientTests method getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent.

@Test
public void getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent() throws Exception {
    // @formatter:off
    String accessTokenSuccessResponse = "{\n" + "	  \"access_token\": \"access-token-1234\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
    // @formatter:on
    this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
    // @formatter:off
    ClientRegistration clientRegistration = this.clientRegistrationBuilder.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).clientSecret(TestKeys.DEFAULT_ENCODED_SECRET_KEY).build();
    // @formatter:on
    // Configure Jwt client authentication converter
    SecretKeySpec secretKey = new SecretKeySpec(clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
    JWK jwk = TestJwks.jwk(secretKey).build();
    Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
    configureJwtClientAuthenticationConverter(jwkResolver);
    OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken);
    this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block();
    RecordedRequest actualRequest = this.server.takeRequest();
    assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=refresh_token", "client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer", "client_assertion=");
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Function(java.util.function.Function) BDDMockito.given(org.mockito.BDDMockito.given) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) MockWebServer(okhttp3.mockwebserver.MockWebServer) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) Converter(org.springframework.core.convert.converter.Converter) TestOAuth2AccessTokenResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses) TestKeys(org.springframework.security.oauth2.jose.TestKeys) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) HttpHeaders(org.springframework.http.HttpHeaders) TestJwks(org.springframework.security.oauth2.jose.TestJwks) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor) Instant(java.time.Instant) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) JWK(com.nimbusds.jose.jwk.JWK) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) MockResponse(okhttp3.mockwebserver.MockResponse) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Collections(java.util.Collections) TestOAuth2RefreshTokens(org.springframework.security.oauth2.core.TestOAuth2RefreshTokens) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Mockito.mock(org.mockito.Mockito.mock) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) SecretKeySpec(javax.crypto.spec.SecretKeySpec) JWK(com.nimbusds.jose.jwk.JWK) Test(org.junit.jupiter.api.Test)

Example 5 with OAuth2RefreshTokenGrantRequest

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

the class WebClientReactiveRefreshTokenTokenResponseClientTests method getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent.

@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
    // @formatter:off
    String accessTokenSuccessResponse = "{\n" + "	  \"access_token\": \"access-token-1234\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
    // @formatter:on
    this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
    // @formatter:off
    ClientRegistration clientRegistration = this.clientRegistrationBuilder.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).build();
    // @formatter:on
    // Configure Jwt client authentication converter
    JWK jwk = TestJwks.DEFAULT_RSA_JWK;
    Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
    configureJwtClientAuthenticationConverter(jwkResolver);
    OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken);
    this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block();
    RecordedRequest actualRequest = this.server.takeRequest();
    assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=refresh_token", "client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer", "client_assertion=");
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Function(java.util.function.Function) BDDMockito.given(org.mockito.BDDMockito.given) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) MockWebServer(okhttp3.mockwebserver.MockWebServer) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) Converter(org.springframework.core.convert.converter.Converter) TestOAuth2AccessTokenResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses) TestKeys(org.springframework.security.oauth2.jose.TestKeys) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) HttpHeaders(org.springframework.http.HttpHeaders) TestJwks(org.springframework.security.oauth2.jose.TestJwks) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor) Instant(java.time.Instant) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) JWK(com.nimbusds.jose.jwk.JWK) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) MockResponse(okhttp3.mockwebserver.MockResponse) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Collections(java.util.Collections) TestOAuth2RefreshTokens(org.springframework.security.oauth2.core.TestOAuth2RefreshTokens) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Mockito.mock(org.mockito.Mockito.mock) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWK(com.nimbusds.jose.jwk.JWK) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)17 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)12 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)11 Instant (java.time.Instant)7 HttpHeaders (org.springframework.http.HttpHeaders)7 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)7 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)7 Collections (java.util.Collections)5 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)5 JWK (com.nimbusds.jose.jwk.JWK)4 StandardCharsets (java.nio.charset.StandardCharsets)4 Function (java.util.function.Function)4 SecretKeySpec (javax.crypto.spec.SecretKeySpec)4 MockResponse (okhttp3.mockwebserver.MockResponse)4 MockWebServer (okhttp3.mockwebserver.MockWebServer)4 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)4 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)4 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)4 AfterEach (org.junit.jupiter.api.AfterEach)4