Search in sources :

Example 31 with OAuth2AuthorizationContext

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

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

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

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

the class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager method createAuthorizationContext.

private Mono<OAuth2AuthorizationContext> createAuthorizationContext(OAuth2AuthorizeRequest authorizeRequest) {
    String clientRegistrationId = authorizeRequest.getClientRegistrationId();
    Authentication principal = authorizeRequest.getPrincipal();
    return Mono.justOrEmpty(authorizeRequest.getAuthorizedClient()).map(OAuth2AuthorizationContext::withAuthorizedClient).switchIfEmpty(Mono.defer(() -> this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId).flatMap((clientRegistration) -> this.authorizedClientService.loadAuthorizedClient(clientRegistrationId, principal.getName()).map(OAuth2AuthorizationContext::withAuthorizedClient).switchIfEmpty(Mono.fromSupplier(() -> OAuth2AuthorizationContext.withClientRegistration(clientRegistration)))).switchIfEmpty(Mono.error(() -> new IllegalArgumentException("Could not find ClientRegistration with id '" + clientRegistrationId + "'"))))).flatMap((contextBuilder) -> this.contextAttributesMapper.apply(authorizeRequest).defaultIfEmpty(Collections.emptyMap()).map((contextAttributes) -> {
        OAuth2AuthorizationContext.Builder builder = contextBuilder.principal(principal);
        if (!contextAttributes.isEmpty()) {
            builder = builder.attributes((attributes) -> attributes.putAll(contextAttributes));
        }
        return builder.build();
    }));
}
Also used : DefaultReactiveOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) Map(java.util.Map) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) Mono(reactor.core.publisher.Mono) Authentication(org.springframework.security.core.Authentication) Collections(java.util.Collections) Function(java.util.function.Function) Assert(org.springframework.util.Assert) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Authentication(org.springframework.security.core.Authentication)

Example 35 with OAuth2AuthorizationContext

use of org.springframework.security.oauth2.client.OAuth2AuthorizationContext 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)

Aggregations

Test (org.junit.jupiter.api.Test)67 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)31 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)30 Instant (java.time.Instant)21 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)21 OAuth2AuthorizeRequest (org.springframework.security.oauth2.client.OAuth2AuthorizeRequest)21 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)19 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)17 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)15 Authentication (org.springframework.security.core.Authentication)14 Function (java.util.function.Function)11 ClientAuthorizationException (org.springframework.security.oauth2.client.ClientAuthorizationException)11 Map (java.util.Map)10 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)10 HashMap (java.util.HashMap)9 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)9 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)9 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)9 BeforeEach (org.junit.jupiter.api.BeforeEach)9