在Spring Cloud Gateway中自定义请求

时间:2020-01-13 17:19:10

标签: spring spring-boot spring-cloud spring-cloud-gateway

据我所知,Spring Cloud Gateway必须实现一个HTTP客户端来发出反向代理请求。 Spring框架仅提供WebClient。我不知道Spring Cloud Gateway是否真正在内部使用它。

如果可以,是否可以访问WebClient实例?这将允许配置客户端的属性。一种可能性是提供一个OAuth2授权客户端,以使用Authorization标头配置请求,例如here

WebClient webClient;
@RegisteredOAuth2AuthorizedClient("client-id") OAuth2AuthorizedClient authorizedClient;

this.webClient
            .get()
            .uri(this.uri)
            .attributes(oauth2AuthorizedClient(authorizedClient));

要做的是将其与密码授权授予类型集成在一起,Spring没有提供一种顺利进行此操作的方法。 Here您可以找到有关这种情况的更多信息。

1 个答案:

答案 0 :(得分:1)

实际上,不需要手动拦截您的呼叫。有很多教程讲解如何在Spring Cloud Gateway上启用OAuth2授权的方法。 您可以关注this part of the official tutorial。您可以在this Okta related guideline page上找到有用的信息。或者这是我以前使用的代码:

/**
 * OAuth2.0 authorization filter setup.
 *
 * @param http
 * @return security filter
 */
@Bean
@ConditionalOnMissingBean
public SecurityWebFilterChain springSecurityFilterChainWithAuth(ServerHttpSecurity http) {
    http
            .authorizeExchange()
            .anyExchange().authenticated()
            .and()
            .oauth2ResourceServer()
            .jwt();
    return http.build();
}

属性文件中的其他配置:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: [your_uri_here]