Search in sources :

Example 71 with OAuth2AuthorizedClient

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

the class PasswordReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenPasswordAndAuthorizedWithRefreshTokenAndTokenExpiredThenNotReauthorize.

@Test
public void authorizeWhenPasswordAndAuthorizedWithRefreshTokenAndTokenExpiredThenNotReauthorize() {
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-expired", issuedAt, expiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), accessToken, // with
    TestOAuth2RefreshTokens.refreshToken());
    // refresh
    // token
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username").attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password").principal(this.principal).build();
    // @formatter:on
    assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test)

Example 72 with OAuth2AuthorizedClient

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

the class PasswordReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenPasswordAndAuthorizedWithoutRefreshTokenAndTokenExpiredThenReauthorize.

@Test
public void authorizeWhenPasswordAndAuthorizedWithoutRefreshTokenAndTokenExpiredThenReauthorize() {
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-expired", issuedAt, expiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), // without refresh token
    accessToken);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username").attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password").principal(this.principal).build();
    // @formatter:on
    authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
    assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test)

Example 73 with OAuth2AuthorizedClient

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

the class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenAuthorizedAndAccessTokenNotExpiredButClockSkewForcesExpiryThenReauthorize.

// gh-7511
@Test
public void authorizeWhenAuthorizedAndAccessTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("new-refresh-token").build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    Instant now = Instant.now();
    Instant issuedAt = now.minus(Duration.ofMinutes(60));
    Instant expiresAt = now.minus(Duration.ofMinutes(1));
    OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", issuedAt, expiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), expiresInOneMinAccessToken, this.authorizedClient.getRefreshToken());
    // Shorten the lifespan of the access token by 90 seconds, which will ultimately
    // force it to expire on the client
    this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
    OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
    assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
    assertThat(reauthorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test)

Example 74 with OAuth2AuthorizedClient

use of org.springframework.security.oauth2.client.OAuth2AuthorizedClient 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 75 with OAuth2AuthorizedClient

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

the class AuthorizedClientServiceOAuth2AuthorizedClientManager method authorize.

@Nullable
@Override
public OAuth2AuthorizedClient authorize(OAuth2AuthorizeRequest authorizeRequest) {
    Assert.notNull(authorizeRequest, "authorizeRequest cannot be null");
    String clientRegistrationId = authorizeRequest.getClientRegistrationId();
    OAuth2AuthorizedClient authorizedClient = authorizeRequest.getAuthorizedClient();
    Authentication principal = authorizeRequest.getPrincipal();
    OAuth2AuthorizationContext.Builder contextBuilder;
    if (authorizedClient != null) {
        contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
    } else {
        ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
        Assert.notNull(clientRegistration, "Could not find ClientRegistration with id '" + clientRegistrationId + "'");
        authorizedClient = this.authorizedClientService.loadAuthorizedClient(clientRegistrationId, principal.getName());
        if (authorizedClient != null) {
            contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
        } else {
            contextBuilder = OAuth2AuthorizationContext.withClientRegistration(clientRegistration);
        }
    }
    OAuth2AuthorizationContext authorizationContext = buildAuthorizationContext(authorizeRequest, principal, contextBuilder);
    try {
        authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
    } catch (OAuth2AuthorizationException ex) {
        this.authorizationFailureHandler.onAuthorizationFailure(ex, principal, Collections.emptyMap());
        throw ex;
    }
    if (authorizedClient != null) {
        this.authorizationSuccessHandler.onAuthorizationSuccess(authorizedClient, principal, Collections.emptyMap());
    } else {
        // `authorizationContext.authorizedClient`.
        if (authorizationContext.getAuthorizedClient() != null) {
            return authorizationContext.getAuthorizedClient();
        }
    }
    return authorizedClient;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Authentication(org.springframework.security.core.Authentication) Nullable(org.springframework.lang.Nullable)

Aggregations

Test (org.junit.jupiter.api.Test)140 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)123 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)66 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)51 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)45 Instant (java.time.Instant)43 Authentication (org.springframework.security.core.Authentication)41 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)36 ClientRequest (org.springframework.web.reactive.function.client.ClientRequest)34 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)32 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)31 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)31 BeforeEach (org.junit.jupiter.api.BeforeEach)28 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)23 Map (java.util.Map)21 HashMap (java.util.HashMap)20 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)19 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)17 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)17 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)17