Search in sources :

Example 76 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class OAuth2ClientBeanDefinitionParserTests method requestWhenCustomAuthorizedClientServiceThenCalled.

@WithMockUser
@Test
public void requestWhenCustomAuthorizedClientServiceThenCalled() throws Exception {
    this.spring.configLocations(xml("CustomAuthorizedClientService")).autowire();
    ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
    OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest(clientRegistration);
    given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(authorizationRequest);
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", authorizationRequest.getState());
    // @formatter:off
    this.mvc.perform(get(authorizationRequest.getRedirectUri()).params(params)).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl(authorizationRequest.getRedirectUri()));
    // @formatter:on
    verify(this.authorizedClientService).saveAuthorizedClient(any(), any());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) WithMockUser(org.springframework.security.test.context.support.WithMockUser) Test(org.junit.jupiter.api.Test)

Example 77 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse 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 78 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse 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)

Example 79 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class WebClientReactiveClientCredentialsTokenResponseClientTests method setWebClientCustomThenCustomClientIsUsed.

@Test
public void setWebClientCustomThenCustomClientIsUsed() {
    WebClient customClient = mock(WebClient.class);
    given(customClient.post()).willReturn(WebClient.builder().build().post());
    this.client.setWebClient(customClient);
    ClientRegistration registration = this.clientRegistration.build();
    // @formatter:off
    enqueueJson("{\n" + "  \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n" + "  \"token_type\":\"bearer\",\n" + "  \"expires_in\":3600,\n" + "  \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n" + "}");
    // @formatter:on
    OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
    OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
    verify(customClient, atLeastOnce()).post();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) WebClient(org.springframework.web.reactive.function.client.WebClient) Test(org.junit.jupiter.api.Test)

Example 80 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class WebClientReactivePasswordTokenResponseClientTests method getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse.

// gh-10260
@Test
public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse() {
    String accessTokenSuccessResponse = "{}";
    WebClientReactivePasswordTokenResponseClient customClient = new WebClientReactivePasswordTokenResponseClient();
    BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock(BodyExtractor.class);
    OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(extractor.extract(any(), any())).willReturn(Mono.just(response));
    customClient.setBodyExtractor(extractor);
    ClientRegistration clientRegistration = this.clientRegistrationBuilder.build();
    OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, this.username, this.password);
    this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
    OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(passwordGrantRequest).block();
    assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
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)

Aggregations

OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)134 Test (org.junit.jupiter.api.Test)122 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)43 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)40 Instant (java.time.Instant)37 HashMap (java.util.HashMap)32 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)27 Mono (reactor.core.publisher.Mono)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)16 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)16 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)15 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)15 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)14 BeforeEach (org.junit.jupiter.api.BeforeEach)13 Map (java.util.Map)12 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)11 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11