Search in sources :

Example 1 with ServerOAuth2AuthorizedClientExchangeFilterFunction

use of org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction in project graphql-maven-plugin-project by graphql-java-generator.

the class MinimalSpringApp method serverOAuth2AuthorizedClientExchangeFilterFunction.

/**
 * This beans is all that is needed to wire OAuth into the application, thanks to Spring Boot and some configuration
 * lines in the resources/application.properties file
 */
@Bean
ServerOAuth2AuthorizedClientExchangeFilterFunction serverOAuth2AuthorizedClientExchangeFilterFunction(ReactiveClientRegistrationRepository clientRegistrations) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
    oauth.setDefaultClientRegistrationId("provider_test");
    return oauth;
}
Also used : ServerOAuth2AuthorizedClientExchangeFilterFunction(org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction) UnAuthenticatedServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository) Bean(org.springframework.context.annotation.Bean)

Example 2 with ServerOAuth2AuthorizedClientExchangeFilterFunction

use of org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction in project spring-security-samples by spring-projects.

the class WebClientConfiguration method webClient.

@Bean
WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
    oauth.setDefaultOAuth2AuthorizedClient(true);
    // @formatter:off
    return WebClient.builder().baseUrl(this.uri).filter(oauth).build();
// @formatter:on
}
Also used : ServerOAuth2AuthorizedClientExchangeFilterFunction(org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction) Bean(org.springframework.context.annotation.Bean)

Example 3 with ServerOAuth2AuthorizedClientExchangeFilterFunction

use of org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction in project EDUC-PEN-REG-BATCH-API by bcgov.

the class RestWebClient method webClient.

/**
 * Web client web client.
 *
 * @return the web client
 */
@Bean
@Autowired
WebClient webClient(final WebClient.Builder builder) {
    val clientRegistryRepo = new InMemoryReactiveClientRegistrationRepository(ClientRegistration.withRegistrationId(this.props.getClientID()).tokenUri(this.props.getTokenURL()).clientId(this.props.getClientID()).clientSecret(this.props.getClientSecret()).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).build());
    val clientService = new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistryRepo);
    val authorizedClientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(clientRegistryRepo, clientService);
    val oauthFilter = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
    oauthFilter.setDefaultClientRegistrationId(this.props.getClientID());
    return builder.defaultHeader("X-Client-Name", ApplicationProperties.API_NAME).codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(100 * 1024 * 1024)).filter(this.log()).clientConnector(this.connector).uriBuilderFactory(this.factory).filter(oauthFilter).build();
}
Also used : lombok.val(lombok.val) ReactorClientHttpConnector(org.springframework.http.client.reactive.ReactorClientHttpConnector) LogHelper(ca.bc.gov.educ.penreg.api.helpers.LogHelper) lombok.val(lombok.val) Autowired(org.springframework.beans.factory.annotation.Autowired) WebClient(org.springframework.web.reactive.function.client.WebClient) ApplicationProperties(ca.bc.gov.educ.penreg.api.properties.ApplicationProperties) AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager) Profile(org.springframework.context.annotation.Profile) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Configuration(org.springframework.context.annotation.Configuration) InMemoryReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository) ServerOAuth2AuthorizedClientExchangeFilterFunction(org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction) ExchangeFilterFunction(org.springframework.web.reactive.function.client.ExchangeFilterFunction) DefaultUriBuilderFactory(org.springframework.web.util.DefaultUriBuilderFactory) Bean(org.springframework.context.annotation.Bean) InMemoryReactiveOAuth2AuthorizedClientService(org.springframework.security.oauth2.client.InMemoryReactiveOAuth2AuthorizedClientService) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) HttpClient(reactor.netty.http.client.HttpClient) InMemoryReactiveOAuth2AuthorizedClientService(org.springframework.security.oauth2.client.InMemoryReactiveOAuth2AuthorizedClientService) AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager) InMemoryReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository) ServerOAuth2AuthorizedClientExchangeFilterFunction(org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction) Autowired(org.springframework.beans.factory.annotation.Autowired) Bean(org.springframework.context.annotation.Bean)

Example 4 with ServerOAuth2AuthorizedClientExchangeFilterFunction

use of org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction in project spring-security by spring-projects.

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenClientCredentialsClientNotAuthorizedAndOutsideRequestContextThenGetNewToken.

// gh-7544
@Test
public void filterWhenClientCredentialsClientNotAuthorizedAndOutsideRequestContextThenGetNewToken() {
    setupMockHeaders();
    // Use UnAuthenticatedServerOAuth2AuthorizedClientRepository when operating
    // outside of a request context
    ServerOAuth2AuthorizedClientRepository unauthenticatedAuthorizedClientRepository = spy(new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
    this.function = new ServerOAuth2AuthorizedClientExchangeFilterFunction(this.clientRegistrationRepository, unauthenticatedAuthorizedClientRepository);
    this.function.setClientCredentialsTokenResponseClient(this.clientCredentialsTokenResponseClient);
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
    given(this.clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
    given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))).willReturn(Mono.just(registration));
    // @formatter:off
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(registration.getRegistrationId())).build();
    // @formatter:on
    this.function.filter(request, this.exchange).block();
    verify(unauthenticatedAuthorizedClientRepository).loadAuthorizedClient(any(), any(), any());
    verify(this.clientCredentialsTokenResponseClient).getTokenResponse(any());
    verify(unauthenticatedAuthorizedClientRepository).saveAuthorizedClient(any(), any(), any());
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    ClientRequest request1 = requests.get(0);
    assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer new-token");
    assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
    assertThat(request1.method()).isEqualTo(HttpMethod.GET);
    assertThat(getBody(request1)).isEmpty();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) UnAuthenticatedServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) UnAuthenticatedServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 5 with ServerOAuth2AuthorizedClientExchangeFilterFunction

use of org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction in project stream-services-2.0 by Backbase.

the class DbsWebClientConfiguration method dbsWebClient.

/**
 * Default Reactive Web Client to be used when interacting with DBS Services. Requires OAuth2 client credentials set
 * in application.yml
 *
 * @param objectMapper                          The Jackson Object mapper to register serialization and deserialization json
 *                                              content.
 * @param reactiveOAuth2AuthorizedClientManager Client Manager managing OAuth2 tokens
 * @param builder                               THe Web Client Builder which is already preconfigured using MicroMeter
 *                                              instrumentation.
 * @return Preconfigured Web Client
 */
@Bean
public WebClient dbsWebClient(ObjectMapper objectMapper, ReactiveOAuth2AuthorizedClientManager reactiveOAuth2AuthorizedClientManager, WebClient.Builder builder, DbsWebClientConfigurationProperties dbsWebClientConfigurationProperties) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2ClientFilter = new ServerOAuth2AuthorizedClientExchangeFilterFunction(reactiveOAuth2AuthorizedClientManager);
    oauth2ClientFilter.setDefaultClientRegistrationId(dbsWebClientConfigurationProperties.getDefaultClientRegistrationId());
    builder.defaultHeader("Content-Type", MediaType.APPLICATION_JSON.toString()).defaultHeader("Accept", MediaType.APPLICATION_JSON.toString()).filter((clientRequest, exchangeFunction) -> {
        final ClientRequest newRequest = Optional.ofNullable(dbsWebClientConfigurationProperties.getAdditionalHeaders()).map(additionalHeaders -> {
            log.debug("Adding additional headers: {} from configuration  Request: {}", additionalHeaders, clientRequest.url());
            return ClientRequest.from(clientRequest).headers(httpHeaders -> httpHeaders.addAll(additionalHeaders)).build();
        }).orElse(clientRequest);
        return Mono.subscriberContext().flatMap(context -> {
            Optional<MultiValueMap<String, String>> forwardHeaders = context.<MultiValueMap<String, String>>getOrEmpty(CONTEXT_KEY_FORWARDED_HEADERS);
            log.debug("context contains headers? " + forwardHeaders.isPresent());
            log.debug("forward headers:" + forwardHeaders.map(MultiValueMap::toString).orElse("null"));
            ClientRequest contextRequest = context.<MultiValueMap<String, String>>getOrEmpty("headers").map(headers -> {
                log.debug("Adding additional headers: {} from Reactive subscriber context to Request: {}", headers, clientRequest.url());
                return ClientRequest.from(newRequest).headers(httpHeaders -> httpHeaders.addAll(headers)).build();
            }).orElse(newRequest);
            return exchangeFunction.exchange(contextRequest);
        });
    }).filter(new CsrfClientExchangeFilterFunction()).filter(oauth2ClientFilter);
    if (log.isDebugEnabled()) {
        HttpClient httpClient = HttpClient.create().wiretap("reactor.netty.http.client.HttpClient", LogLevel.DEBUG, AdvancedByteBufFormat.TEXTUAL);
        builder.clientConnector(new ReactorClientHttpConnector(httpClient));
    }
    // ensure correct exchange strategy is installed
    ExchangeStrategies strategies = ExchangeStrategies.builder().codecs(clientDefaultCodecsConfigurer -> {
        Jackson2JsonEncoder encoder = new Jackson2JsonEncoder(objectMapper, MediaType.APPLICATION_JSON);
        Jackson2JsonDecoder decoder = new Jackson2JsonDecoder(objectMapper, MediaType.APPLICATION_JSON);
        clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(encoder);
        clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(decoder);
    }).build();
    builder.exchangeStrategies(strategies);
    return builder.build();
}
Also used : java.util(java.util) DbsWebClientConfigurationProperties(com.backbase.stream.webclient.configuration.DbsWebClientConfigurationProperties) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ServerOAuth2AuthorizedClientExchangeFilterFunction(org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction) JavaTimeModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule) org.springframework.web.reactive.function.client(org.springframework.web.reactive.function.client) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) OAuth2ClientProperties(org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties) OAuth2ClientPropertiesRegistrationAdapter(org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter) DateFormat(java.text.DateFormat) ResponseCookie(org.springframework.http.ResponseCookie) ReactorClientHttpConnector(org.springframework.http.client.reactive.ReactorClientHttpConnector) AdvancedByteBufFormat(reactor.netty.transport.logging.AdvancedByteBufFormat) Jackson2JsonDecoder(org.springframework.http.codec.json.Jackson2JsonDecoder) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) MediaType(org.springframework.http.MediaType) org.springframework.security.oauth2.client(org.springframework.security.oauth2.client) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Configuration(org.springframework.context.annotation.Configuration) InMemoryReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository) Slf4j(lombok.extern.slf4j.Slf4j) LogLevel(io.netty.handler.logging.LogLevel) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) StdDateFormat(com.fasterxml.jackson.databind.util.StdDateFormat) Bean(org.springframework.context.annotation.Bean) HttpClient(reactor.netty.http.client.HttpClient) Jackson2JsonDecoder(org.springframework.http.codec.json.Jackson2JsonDecoder) HttpClient(reactor.netty.http.client.HttpClient) ServerOAuth2AuthorizedClientExchangeFilterFunction(org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction) MultiValueMap(org.springframework.util.MultiValueMap) ReactorClientHttpConnector(org.springframework.http.client.reactive.ReactorClientHttpConnector) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) Bean(org.springframework.context.annotation.Bean)

Aggregations

ServerOAuth2AuthorizedClientExchangeFilterFunction (org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction)10 Bean (org.springframework.context.annotation.Bean)8 UnAuthenticatedServerOAuth2AuthorizedClientRepository (org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository)7 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)6 ReactiveClientRegistrationRepository (org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository)5 MediaType (org.springframework.http.MediaType)4 InMemoryReactiveClientRegistrationRepository (org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository)4 Jackson2JsonEncoder (org.springframework.http.codec.json.Jackson2JsonEncoder)3 ServerOAuth2AuthorizedClientRepository (org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository)3 Mono (reactor.core.publisher.Mono)3 DbsWebClientConfigurationProperties (com.backbase.stream.webclient.configuration.DbsWebClientConfigurationProperties)2 JsonInclude (com.fasterxml.jackson.annotation.JsonInclude)2 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 StdDateFormat (com.fasterxml.jackson.databind.util.StdDateFormat)2 JavaTimeModule (com.fasterxml.jackson.datatype.jsr310.JavaTimeModule)2 LogLevel (io.netty.handler.logging.LogLevel)2 URI (java.net.URI)2 DateFormat (java.text.DateFormat)2 java.util (java.util)2