Search in sources :

Example 11 with OAuth2ClientCredentialsGrantRequest

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

the class NimbusJwtClientAuthenticationParametersConverterTests method convertWhenClientKeyChangesThenNewKeyUsed.

// gh-9814
@Test
public void convertWhenClientKeyChangesThenNewKeyUsed() throws Exception {
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).build();
    // @formatter:on
    RSAKey rsaJwk1 = TestJwks.DEFAULT_RSA_JWK;
    given(this.jwkResolver.apply(eq(clientRegistration))).willReturn(rsaJwk1);
    OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
    MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
    String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk1.toRSAPublicKey()).build();
    jwtDecoder.decode(encodedJws);
    RSAKey rsaJwk2 = generateRsaJwk();
    given(this.jwkResolver.apply(eq(clientRegistration))).willReturn(rsaJwk2);
    parameters = this.converter.convert(clientCredentialsGrantRequest);
    encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
    jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk2.toRSAPublicKey()).build();
    jwtDecoder.decode(encodedJws);
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) Test(org.junit.jupiter.api.Test)

Example 12 with OAuth2ClientCredentialsGrantRequest

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

the class WebClientReactiveClientCredentialsTokenResponseClientTests method getTokenResponseWhenHeaderThenSuccess.

@Test
public void getTokenResponseWhenHeaderThenSuccess() throws Exception {
    // @formatter:off
    enqueueJson("{\n" + "  \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n" + "  \"token_type\":\"bearer\",\n" + "  \"expires_in\":3600,\n" + "  \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\",\n" + "  \"scope\":\"create\"\n" + "}");
    // @formatter:on
    OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
    OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
    RecordedRequest actualRequest = this.server.takeRequest();
    String body = actualRequest.getUtf8Body();
    assertThat(response.getAccessToken()).isNotNull();
    assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
    assertThat(body).isEqualTo("grant_type=client_credentials&scope=read%3Auser");
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Test(org.junit.jupiter.api.Test)

Example 13 with OAuth2ClientCredentialsGrantRequest

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

the class ClientCredentialsReactiveOAuth2AuthorizedClientProvider method authorize.

/**
 * Attempt to authorize (or re-authorize) the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
 * {@code context}. Returns an empty {@code Mono} 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 an empty {@code Mono} if
 * authorization (or re-authorization) is not supported
 */
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
    Assert.notNull(context, "context cannot be null");
    ClientRegistration clientRegistration = context.getClientRegistration();
    if (!AuthorizationGrantType.CLIENT_CREDENTIALS.equals(clientRegistration.getAuthorizationGrantType())) {
        return Mono.empty();
    }
    OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
    if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
        // need for re-authorization
        return Mono.empty();
    }
    // is the same as acquiring a new access token (authorization).
    return Mono.just(new OAuth2ClientCredentialsGrantRequest(clientRegistration)).flatMap(this.accessTokenResponseClient::getTokenResponse).onErrorMap(OAuth2AuthorizationException.class, (ex) -> new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex)).map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken()));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) Duration(java.time.Duration) WebClientReactiveClientCredentialsTokenResponseClient(org.springframework.security.oauth2.client.endpoint.WebClientReactiveClientCredentialsTokenResponseClient) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) Clock(java.time.Clock) 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) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest) 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) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest)

Example 14 with OAuth2ClientCredentialsGrantRequest

use of org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest 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 15 with OAuth2ClientCredentialsGrantRequest

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

the class WebClientReactiveClientCredentialsTokenResponseClientTests method getTokenResponseWhenPostThenSuccess.

@Test
public void getTokenResponseWhenPostThenSuccess() throws Exception {
    ClientRegistration registration = this.clientRegistration.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
    // @formatter:off
    enqueueJson("{\n" + "  \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n" + "  \"token_type\":\"bearer\",\n" + "  \"expires_in\":3600,\n" + "  \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\",\n" + "  \"scope\":\"create\"\n" + "}");
    // @formatter:on
    OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
    OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
    RecordedRequest actualRequest = this.server.takeRequest();
    String body = actualRequest.getUtf8Body();
    assertThat(response.getAccessToken()).isNotNull();
    assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    assertThat(body).isEqualTo("grant_type=client_credentials&client_id=client-id&client_secret=client-secret&scope=read%3Auser");
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)28 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)24 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)16 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)10 HttpHeaders (org.springframework.http.HttpHeaders)8 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)5 MultiValueMap (org.springframework.util.MultiValueMap)5 JWK (com.nimbusds.jose.jwk.JWK)4 StandardCharsets (java.nio.charset.StandardCharsets)4 Instant (java.time.Instant)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 BeforeEach (org.junit.jupiter.api.BeforeEach)4 MediaType (org.springframework.http.MediaType)4