Search in sources :

Example 1 with JwtBearerGrantRequest

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

the class JwtBearerGrantRequestEntityConverter method createParameters.

@Override
protected MultiValueMap<String, String> createParameters(JwtBearerGrantRequest jwtBearerGrantRequest) {
    ClientRegistration clientRegistration = jwtBearerGrantRequest.getClientRegistration();
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.add(OAuth2ParameterNames.GRANT_TYPE, jwtBearerGrantRequest.getGrantType().getValue());
    parameters.add(OAuth2ParameterNames.ASSERTION, jwtBearerGrantRequest.getJwt().getTokenValue());
    if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
        parameters.add(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), " "));
    }
    if (ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod()) || ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod())) {
        parameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId());
        parameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret());
    }
    return parameters;
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 2 with JwtBearerGrantRequest

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

the class JwtBearerReactiveOAuth2AuthorizedClientProvider 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#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 an empty {@code Mono} if
 * authorization is not supported
 */
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
    Assert.notNull(context, "context cannot be null");
    ClientRegistration clientRegistration = context.getClientRegistration();
    if (!AuthorizationGrantType.JWT_BEARER.equals(clientRegistration.getAuthorizationGrantType())) {
        return Mono.empty();
    }
    OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
    if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
        // need for re-authorization
        return Mono.empty();
    }
    // @formatter:off
    return this.jwtAssertionResolver.apply(context).map((jwt) -> new JwtBearerGrantRequest(clientRegistration, jwt)).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()));
// @formatter:on
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) Mono(reactor.core.publisher.Mono) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) Instant(java.time.Instant) Function(java.util.function.Function) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Duration(java.time.Duration) Clock(java.time.Clock) WebClientReactiveJwtBearerTokenResponseClient(org.springframework.security.oauth2.client.endpoint.WebClientReactiveJwtBearerTokenResponseClient) Jwt(org.springframework.security.oauth2.jwt.Jwt) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) OAuth2Token(org.springframework.security.oauth2.core.OAuth2Token) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest) Assert(org.springframework.util.Assert) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest)

Example 3 with JwtBearerGrantRequest

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

the class WebClientReactiveJwtBearerTokenResponseClientTests method getTokenResponseWhenBodyExtractorSetThenCalled.

@Test
public void getTokenResponseWhenBodyExtractorSetThenCalled() {
    BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> bodyExtractor = mock(BodyExtractor.class);
    OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(bodyExtractor.extract(any(), any())).willReturn(Mono.just(response));
    ClientRegistration clientRegistration = this.clientRegistration.build();
    JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
    this.client.setBodyExtractor(bodyExtractor);
    enqueueJson(DEFAULT_ACCESS_TOKEN_RESPONSE);
    this.client.getTokenResponse(request).block();
    verify(bodyExtractor).extract(any(), any());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Mono(reactor.core.publisher.Mono) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) Test(org.junit.jupiter.api.Test)

Example 4 with JwtBearerGrantRequest

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

the class WebClientReactiveJwtBearerTokenResponseClientTests method getTokenResponseWhenInvalidResponseThenThrowOAuth2AuthorizationException.

@Test
public void getTokenResponseWhenInvalidResponseThenThrowOAuth2AuthorizationException() {
    ClientRegistration registration = this.clientRegistration.build();
    enqueueUnexpectedResponse();
    JwtBearerGrantRequest request = new JwtBearerGrantRequest(registration, this.jwtAssertion);
    assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> this.client.getTokenResponse(request).block()).satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response")).withMessage("[invalid_token_response] Empty OAuth 2.0 Access Token Response");
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) WebClient(org.springframework.web.reactive.function.client.WebClient) 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) Jwt(org.springframework.security.oauth2.jwt.Jwt) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) Converter(org.springframework.core.convert.converter.Converter) TestOAuth2AccessTokenResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) 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) Collections(java.util.Collections) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Mockito.mock(org.mockito.Mockito.mock) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Test(org.junit.jupiter.api.Test)

Example 5 with JwtBearerGrantRequest

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

the class WebClientReactiveJwtBearerTokenResponseClientTests method getTokenResponseWhenHeadersConverterSetThenCalled.

@Test
public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception {
    ClientRegistration clientRegistration = this.clientRegistration.build();
    JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
    Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock(Converter.class);
    HttpHeaders headers = new HttpHeaders();
    headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
    given(headersConverter.convert(request)).willReturn(headers);
    this.client.setHeadersConverter(headersConverter);
    enqueueJson(DEFAULT_ACCESS_TOKEN_RESPONSE);
    this.client.getTokenResponse(request).block();
    verify(headersConverter).convert(request);
    RecordedRequest actualRequest = this.server.takeRequest();
    assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) HttpHeaders(org.springframework.http.HttpHeaders) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) 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