【问题标题】:Adding client secret and client id to request in API Gateway在 API Gateway 中添加客户端密钥和客户端 ID 以请求
【发布时间】:2020-07-23 14:27:35
【问题描述】:

我的 Spring Cloud Gateway 后面有一个 Auth 服务器。我想通过网关执行 JWT 身份验证。当我调用相应的 API 端点时,我必须传递我的用户名、密码、客户端 ID 和客户端密码来生成 JWT 令牌。

用户只需使用用户名和密码调用端点,API网关在附加client-id和client-secret后将请求转发到Auth服务器。这是我的全部计划。

我的问题是,如何使用 Spring Cloud Gateway 将客户端 ID 和客户端密码附加到我的请求中?

提前致谢!

【问题讨论】:

  • client id 和 client secret 从何而来?
  • 我创建了一个带有服务器微服务的 OAuth2.0。这就是我的客户 ID 和客户密码的来源

标签: spring oauth-2.0 microservices spring-cloud spring-cloud-gateway


【解决方案1】:

您可以创建如下所示的java配置:

@Configuration
public class SpringCloudConfig {

    @Bean
    public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/oauth/token")
                        .uri("http://localhost:8081/oauth/token")
                        .id("auth"))
                .build();
    }
}

在这种情况下,原始请求和响应将简单地通过spring cloud gateway进行代理。

比如spring cloud gateway运行在8080端口,请求会是(授权服务器运行在8081端口):

curl --location --request POST 'http://localhost:8080/oauth/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic c2VydmVyX2FwcDpzZWNyZXQ=' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id=server_app'

您可以在客户端上添加 client-id、client-secret 或其他数据。

如果需要修改请求体可以添加过滤器:

@Configuration
public class SpringCloudConfig {

    @Bean
    public RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/oauth/token")
                        .filters(f -> f.modifyRequestBody(String.class, String.class, MediaType.APPLICATION_JSON_VALUE,
                                (exchange, body) -> {
                                    String modifiedBody = someService.modify(body);
                                    return Mono.just(modifiedBody);
                                })
                        )
                        .uri("http://localhost:8081/oauth/token")
                        .id("auth"))
                .build();
    }
}

【讨论】:

  • 这个我知道。但是这里用户在请求本身中指定了客户端 ID 和密码。在我的问题中,用户只提供用户名和密码。 Spring Cloud Gateway 将在请求中添加客户端 ID 和客户端密码
  • 在最后一个示例中,我使用过滤器修改了正文。您可以使用此过滤器将 client-id 或 client-secret 添加到正文。如有必要,您可以以相同的方式添加/更改标题。附加检查取决于应用程序逻辑,但无论如何,授权服务都会检查正确性。
  • 如说明所示,无法通过 yml 修改 body - cloud.spring.io/spring-cloud-gateway/reference/html/… ("此过滤器只能使用 Java DSL 配置。")
  • 例如,如果设置:MediaType.APPLICATION_FORM_URLENCODED_VALUE,则可以将此字符串替换为:String modifiedBody = "client-id=test_client&client-secret=secret";但这取决于您的授权服务。
  • SomeService 是指spring cloud gateway应用中的一个类,可以用来修改body。这只是一个示例,您可以删除 someService 并根据您的 MediaType 写入一个字符串。
猜你喜欢
  • 1970-01-01
  • 2017-11-16
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 2018-05-19
  • 2016-01-17
  • 1970-01-01
相关资源
最近更新 更多