Search in sources :

Example 61 with OAuth2AccessTokenResponse

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

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

the class OAuth2ClientConfigurerTests method setup.

@BeforeEach
public void setup() {
    // @formatter:off
    this.registration1 = TestClientRegistrations.clientRegistration().registrationId("registration-1").clientId("client-1").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/client-1").scope("user").authorizationUri("https://provider.com/oauth2/authorize").tokenUri("https://provider.com/oauth2/token").userInfoUri("https://provider.com/oauth2/user").userNameAttributeName("id").clientName("client-1").build();
    // @formatter:on
    clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1);
    authorizedClientService = new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
    authorizedClientRepository = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService);
    authorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository, "/oauth2/authorization");
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(300).build();
    accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
    given(accessTokenResponseClient.getTokenResponse(any(OAuth2AuthorizationCodeGrantRequest.class))).willReturn(accessTokenResponse);
    requestCache = mock(RequestCache.class);
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) RequestCache(org.springframework.security.web.savedrequest.RequestCache) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) InMemoryOAuth2AuthorizedClientService(org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService) InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) AuthenticatedPrincipalOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) DefaultOAuth2AuthorizationRequestResolver(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 63 with OAuth2AccessTokenResponse

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

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project jhipster-registry by jhipster.

the class AuthorizationHeaderUtil method refreshTokenClient.

private OAuth2AccessTokenResponse refreshTokenClient(OAuth2AuthorizedClient currentClient) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue());
    formParameters.add(OAuth2ParameterNames.REFRESH_TOKEN, currentClient.getRefreshToken().getTokenValue());
    formParameters.add(OAuth2ParameterNames.CLIENT_ID, currentClient.getClientRegistration().getClientId());
    RequestEntity requestEntity = RequestEntity.post(URI.create(currentClient.getClientRegistration().getProviderDetails().getTokenUri())).contentType(MediaType.APPLICATION_FORM_URLENCODED).body(formParameters);
    try {
        RestTemplate r = restTemplate(currentClient.getClientRegistration().getClientId(), currentClient.getClientRegistration().getClientSecret());
        ResponseEntity<OAuthIdpTokenResponseDTO> responseEntity = r.exchange(requestEntity, OAuthIdpTokenResponseDTO.class);
        return toOAuth2AccessTokenResponse(responseEntity.getBody());
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to refresh token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) RequestEntity(org.springframework.http.RequestEntity) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 65 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project jhipster-registry by jhipster.

the class AuthorizationHeaderUtil method refreshToken.

private String refreshToken(OAuth2AuthorizedClient client, OAuth2AuthenticationToken oauthToken) {
    OAuth2AccessTokenResponse atr = refreshTokenClient(client);
    if (atr == null || atr.getAccessToken() == null) {
        log.info("Failed to refresh token for user");
        return null;
    }
    OAuth2RefreshToken refreshToken = atr.getRefreshToken() != null ? atr.getRefreshToken() : client.getRefreshToken();
    OAuth2AuthorizedClient updatedClient = new OAuth2AuthorizedClient(client.getClientRegistration(), client.getPrincipalName(), atr.getAccessToken(), refreshToken);
    clientService.saveAuthorizedClient(updatedClient, oauthToken);
    return atr.getAccessToken().getTokenValue();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient)

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