Search in sources :

Example 11 with JwtBearerGrantRequest

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

the class DefaultJwtBearerTokenResponseClientTests method getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope.

@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope() throws Exception {
    // @formatter:off
    String accessTokenSuccessResponse = "{\n" + "   \"access_token\": \"access-token-1234\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\",\n" + "   \"scope\": \"read\"\n" + "}\n";
    // @formatter:on
    this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
    JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(), this.jwtAssertion);
    OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest);
    assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Test(org.junit.jupiter.api.Test)

Example 12 with JwtBearerGrantRequest

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

the class DefaultJwtBearerTokenResponseClientTests method getTokenResponseWhenAuthenticationClientSecretPostThenFormParametersAreSent.

@Test
public void getTokenResponseWhenAuthenticationClientSecretPostThenFormParametersAreSent() 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));
    ClientRegistration clientRegistration = this.clientRegistration.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
    JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
    this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest);
    RecordedRequest recordedRequest = this.server.takeRequest();
    assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    String formParameters = recordedRequest.getBody().readUtf8();
    assertThat(formParameters).contains("client_id=client-1");
    assertThat(formParameters).contains("client_secret=secret");
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Test(org.junit.jupiter.api.Test)

Example 13 with JwtBearerGrantRequest

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

the class JwtBearerOAuth2AuthorizedClientProvider 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#JWT_BEARER
 * jwt-bearer} 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 is not
 * supported
 */
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
    Assert.notNull(context, "context cannot be null");
    ClientRegistration clientRegistration = context.getClientRegistration();
    if (!AuthorizationGrantType.JWT_BEARER.equals(clientRegistration.getAuthorizationGrantType())) {
        return null;
    }
    OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
    if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
        // need for re-authorization
        return null;
    }
    Jwt jwt = this.jwtAssertionResolver.apply(context);
    if (jwt == null) {
        return null;
    }
    // As per spec, in section 4.1 Using Assertions as Authorization Grants
    // https://tools.ietf.org/html/rfc7521#section-4.1
    // 
    // An assertion used in this context is generally a short-lived
    // representation of the authorization grant, and authorization servers
    // SHOULD NOT issue access tokens with a lifetime that exceeds the
    // validity period of the assertion by a significant period. In
    // practice, that will usually mean that refresh tokens are not issued
    // in response to assertion grant requests, and access tokens will be
    // issued with a reasonably short lifetime. Clients can refresh an
    // expired access token by requesting a new one using the same
    // assertion, if it is still valid, or with a new assertion.
    JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwt);
    OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, jwtBearerGrantRequest);
    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) Jwt(org.springframework.security.oauth2.jwt.Jwt) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest) Nullable(org.springframework.lang.Nullable)

Example 14 with JwtBearerGrantRequest

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

the class JwtBearerGrantRequestTests method constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException.

@Test
public void constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException() {
    ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
    assertThatIllegalArgumentException().isThrownBy(() -> new JwtBearerGrantRequest(registration, this.jwtAssertion)).withMessage("clientRegistration.authorizationGrantType must be AuthorizationGrantType.JWT_BEARER");
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Test(org.junit.jupiter.api.Test)

Example 15 with JwtBearerGrantRequest

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

the class JwtBearerGrantRequestEntityConverterTests method convertWhenGrantRequestValidThenConverts.

@SuppressWarnings("unchecked")
@Test
public void convertWhenGrantRequestValidThenConverts() {
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().authorizationGrantType(AuthorizationGrantType.JWT_BEARER).scope("read", "write").build();
    // @formatter:on
    Jwt jwtAssertion = TestJwts.jwt().build();
    JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwtAssertion);
    RequestEntity<?> requestEntity = this.converter.convert(jwtBearerGrantRequest);
    assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
    assertThat(requestEntity.getUrl().toASCIIString()).isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
    HttpHeaders headers = requestEntity.getHeaders();
    assertThat(headers.getAccept()).contains(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
    assertThat(headers.getContentType()).isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
    assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
    MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
    assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE)).isEqualTo(AuthorizationGrantType.JWT_BEARER.getValue());
    assertThat(formParameters.getFirst(OAuth2ParameterNames.ASSERTION)).isEqualTo(jwtAssertion.getTokenValue());
    assertThat(formParameters.getFirst(OAuth2ParameterNames.SCOPE)).isEqualTo("read write");
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Jwt(org.springframework.security.oauth2.jwt.Jwt) MultiValueMap(org.springframework.util.MultiValueMap) Test(org.junit.jupiter.api.Test)

Aggregations

ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)22 Test (org.junit.jupiter.api.Test)21 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)12 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)11 Jwt (org.springframework.security.oauth2.jwt.Jwt)8 HttpHeaders (org.springframework.http.HttpHeaders)7 MultiValueMap (org.springframework.util.MultiValueMap)7 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)6 Mono (reactor.core.publisher.Mono)5 ReactiveHttpInputMessage (org.springframework.http.ReactiveHttpInputMessage)4 AuthorizationGrantType (org.springframework.security.oauth2.core.AuthorizationGrantType)4 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)4 WebClient (org.springframework.web.reactive.function.client.WebClient)4 Collections (java.util.Collections)3 MockResponse (okhttp3.mockwebserver.MockResponse)3 MockWebServer (okhttp3.mockwebserver.MockWebServer)3 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)3 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)3 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)3 AfterEach (org.junit.jupiter.api.AfterEach)3