具有自定义身份验证服务器客户端凭据的spring云网关与webclient一起流动

vc6uscn9  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(364)

我关注了这个博客,如何使用client_凭据从资源服务器访问另一个oauth2资源?创建一个webclient,它将请求令牌并将其转发到另一个资源服务器。这似乎工作正常,因为代码显示它正在使用webclient。
现在,我有了一个SpringCloudGateway,它希望这样做,并请求一个令牌,然后将其转发到下游的资源服务器。
我有以下配置。

@EnableWebFluxSecurity
public class WebClientConfig {

  @Bean
  public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
      ReactiveClientRegistrationRepository clientRegistrationRepository,
      ReactiveOAuth2AuthorizedClientService authorizedClientService) {

    ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
        ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
            .clientCredentials()
            .build();

    AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager =
        new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
            clientRegistrationRepository, authorizedClientService);

    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

    return authorizedClientManager;
  }

  @Bean
  public WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
    String registrationId = "custom";

    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(
        authorizedClientManager);

    oauth.setDefaultClientRegistrationId(registrationId);
    return WebClient.builder()
        .baseUrl("http://localhost:8888")
        .filter(oauth).build();
  }

  @Bean
  public SecurityWebFilterChain configure(ServerHttpSecurity http) {
    return http
        .oauth2Client()
        .and()
        .build();
  }
}

下面是我的application.yml

server:
  port: 8081
spring:
  security:
    oauth2:
      client:
        provider:
          custom:
            token-uri: http://localhost:8080/oauth/token
        registration:
          custom:
            client-id: campaign-station-client
            client-secret: password
            scope: "*"
            authorization-grant-type: client_credentials
  cloud:
    gateway:
      routes:
        - id: resource_server_id
          uri: http://localhost:8888/
          predicates:
            - Path=/resourceserver/**
          filters:
            - RewritePath=/resourceserver/(?<segment>.*), /$\{segment}

当我通过网关调用资源服务器端点时,网关不使用webclient检索访问令牌(例如客户端凭据流)。如何在每次对网关的调用中使用此webclient,以便将令牌转发到下游的资源服务器?

zbsbpyhn

zbsbpyhn1#

您需要编写一个自定义筛选器,然后可以从那里传递令牌。请查看tokengatewayfilter的代码。那会给你一个更好的主意。我也实施了同样的措施。

相关问题