Search in sources :

Example 71 with Mono

use of reactor.core.publisher.Mono in project spring-security by spring-projects.

the class WebClientReactiveClientCredentialsTokenResponseClientTests method getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse.

// gh-10260
@Test
public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse() {
    enqueueJson("{}");
    WebClientReactiveClientCredentialsTokenResponseClient customClient = new WebClientReactiveClientCredentialsTokenResponseClient();
    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);
    OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
    OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(request).block();
    assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Mono(reactor.core.publisher.Mono) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) Test(org.junit.jupiter.api.Test)

Example 72 with Mono

use of reactor.core.publisher.Mono 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 73 with Mono

use of reactor.core.publisher.Mono 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 74 with Mono

use of reactor.core.publisher.Mono in project spring-security by spring-projects.

the class AuthenticationPrincipalArgumentResolverTests method resolveArgumentWhenMonoAndAuthenticationPrincipalThenFound.

@Test
public void resolveArgumentWhenMonoAndAuthenticationPrincipalThenFound() {
    Authentication authentication = TestAuthentication.authenticatedUser();
    // @formatter:off
    Mono<UserDetails> result = (Mono<UserDetails>) this.resolver.resolveArgument(arg0("currentUserOnMonoUserDetails"), null).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)).block();
    // @formatter:on
    assertThat(result.block()).isEqualTo(authentication.getPrincipal());
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) TestAuthentication(org.springframework.security.authentication.TestAuthentication) Authentication(org.springframework.security.core.Authentication) Mono(reactor.core.publisher.Mono) Test(org.junit.jupiter.api.Test)

Example 75 with Mono

use of reactor.core.publisher.Mono in project spring-security by spring-projects.

the class CurrentSecurityContextArgumentResolverTests method resolveArgumentWhenAuthenticationPrincipalThenFound.

@Test
public void resolveArgumentWhenAuthenticationPrincipalThenFound() {
    Authentication authentication = TestAuthentication.authenticatedUser();
    Mono<SecurityContext> result = (Mono<SecurityContext>) this.resolver.resolveArgument(arg0("currentSecurityContextOnMonoSecurityContext"), null).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)).block();
    assertThat(result.block().getAuthentication()).isEqualTo(authentication);
}
Also used : TestAuthentication(org.springframework.security.authentication.TestAuthentication) Authentication(org.springframework.security.core.Authentication) Mono(reactor.core.publisher.Mono) CurrentSecurityContext(org.springframework.security.core.annotation.CurrentSecurityContext) SecurityContext(org.springframework.security.core.context.SecurityContext) Test(org.junit.jupiter.api.Test)

Aggregations

Mono (reactor.core.publisher.Mono)308 Test (org.junit.jupiter.api.Test)143 StepVerifier (reactor.test.StepVerifier)117 List (java.util.List)116 Flux (reactor.core.publisher.Flux)110 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)102 Collections (java.util.Collections)85 Map (java.util.Map)75 HttpStatus (org.springframework.http.HttpStatus)66 ServerWebExchange (org.springframework.web.server.ServerWebExchange)65 Duration (java.time.Duration)60 ArrayList (java.util.ArrayList)58 Test (org.junit.Test)53 MockServerHttpRequest (org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest)52 DataBuffer (org.springframework.core.io.buffer.DataBuffer)51 Assert (org.springframework.util.Assert)49 Mockito.mock (org.mockito.Mockito.mock)48 MockServerWebExchange (org.springframework.web.testfixture.server.MockServerWebExchange)46 Optional (java.util.Optional)44 StandardCharsets (java.nio.charset.StandardCharsets)43