标签: spring-cloud-gateway

Spring Boot 使用带有 Oauth2 的云网关

我的问题是 Oauth2 的 Cloudgateway 安全性。但是,Oauth2 的配置@EnableOAuth2Sso会导致以下错误:

描述:

org.springframework.cloud.gateway.config.GatewayAutoConfiguration 中方法 modifyRequestBodyGatewayFilterFactory 的参数 0 需要一个无法找到的“org.springframework.http.codec.ServerCodecConfigurer”类型的 bean。

行动:

考虑在您的配置中定义一个 'org.springframework.http.codec.ServerCodecConfigurer' 类型的 bean。

当我在 Eureka 上对 Zuul 代理执行相同操作时,一切正常。请帮助我如何解决这个问题。

这是 Cloudgateway 项目,我正在尝试使其成为 Oauth2 客户端:

配置:

@Configuration
@EnableOAuth2Sso
public class UiSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/", "/login**")
                .permitAll()
                .anyRequest()
                .authenticated();
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序.yml:

server:
  port: 8080
  servlet:
    session:
      cookie:
        name: UISESSION
security:
  oauth2:
    client:
      clientId: SampleClientId
      clientSecret: secret
      accessTokenUri: http://localhost:8085/auth/oauth/token
      userAuthorizationUri: http://localhost:8085/auth/oauth/authorize
    resource:
      userInfoUri: http://localhost:8085/auth/principal …
Run Code Online (Sandbox Code Playgroud)

java oauth-2.0 spring-boot spring-security-oauth2 spring-cloud-gateway

1
推荐指数
1
解决办法
4993
查看次数

从zuul迁移到spring cloud gateway时如何“删除全局前缀('/api')然后转到lb://”

我想从 zuul 迁移到 spring 云网关,我不想更改我以前的应用程序的配置。我想知道如何处理带有“/api/ + 'serviceId'”的 url,路由到 lb://serviceId

之前的 zuul 配置

zuul: 
  prefix: /api
Run Code Online (Sandbox Code Playgroud)

eureka 有很多服务注册,我不想为每个服务注册一个路由。

例如。由 org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator 自动生成的路由

{
"route_id": "CompositeDiscoveryClient_APIGATEWAY",
"route_definition": {
  "id": "CompositeDiscoveryClient_APIGATEWAY",
  "predicates": [
    {
      "name": "Path",
      "args": {
        "pattern": "/apigateway/**"
      }
    }
  ],
  "filters": [
    {
      "name": "RewritePath",
      "args": {
        "regexp": "/apigateway/(?<remaining>.*)",
        "replacement": "/${remaining}"
      }
    }
  ],
  "uri": "lb://APIGATEWAY",
  "order": 0
}
Run Code Online (Sandbox Code Playgroud)

我想要的是

 {
"route_id": "CompositeDiscoveryClient_APIGATEWAY",
"route_definition": {
  "id": "CompositeDiscoveryClient_APIGATEWAY",
  "predicates": [
    {
      "name": "Path",
      "args": {
        "pattern": "/api/apigateway/**"
      }
    }
  ],
  "filters": [ …
Run Code Online (Sandbox Code Playgroud)

java spring-cloud netflix-zuul spring-cloud-gateway

1
推荐指数
1
解决办法
2486
查看次数

Spring Cloud Gateway 自定义过滤器工厂的单元测试

我已经为 Cloud Gateway 实现了自定义过滤器工厂。但是,我无法弄清楚编写单元测试用例的方法。在探索默认的过滤器工厂测试用例时,我发现大多数工厂测试类扩展了BaseWebClientTests和测试包中的其他类。

我的问题是我应该将这些中间测试类复制粘贴到我的本地测试包中吗?这里的社区推荐是什么?

java spring spring-cloud spring-cloud-gateway

1
推荐指数
1
解决办法
2506
查看次数

找不到类 org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken 的提供程序

我创建了三个应用程序“spring cloud gateway(8081)”、“spring oauth2 auth server(8094)”和“spring oauth2 Resource server(8097)”。

\n\n

当我想请求资源服务器时,首先我需要请求 gw,它转发到 oauth 服务器,然后我登录那里(oauth 也有 spring 安全层)。成功登录后,它会重定向到后台 gw 服务器,例如http://localhost:8081/login/oauth2/code/gateway?code=6ldKVF&state=0WvvWdTs8G_XchSTQKqgokua_XDVQziqVZ_VXLMqIS0%3D url。然后,屏幕上发生错误。

\n\n

当我在身份验证服务器成功登录时,网关服务器控制台中有一个跟踪日志:

\n\n
\n

2020-01-17 17:52:11.825 跟踪 11336 --- [ctor-http-nio-4]\n oshttp.codec.json.Jackson2JsonDecoder :[21762c89] 已解码\n [{access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOls ib2F1dGgyLXJlc291cmNlIl0sInVzZXJfbmFtZSI6ImRnIiwic2NvcGUIOlsiY3VzdG9tX21vZCJdLCJleHAiOjE1NzkyNzI3NDEsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiowu zYzQ2YTQtMDJiZi00MTgwLTg1ZTktMGJhOTM0MjBhYjg4IiwiY2xpZW50X2lkIjoiZmlyc3QtY2xpZW50In0.xdWGm420tvp2Rzq0AyCgOTcDuKvP- V6JFd76KmJJf7o,\n token_type=承载,\n refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsib2F1dGgyLXJlc291cmNlIl0sInVzZXJfbmFtZSI6ImRnIiwic2NvcGUiOlsiY3Vz dG9tX21vZCJdLCJhdGkiOiI5ZTNjNDZhNC0wMmJmLTQxODAtODVLOS0wYmE5MzQyMGFiODgiLCJleHAiOjE1NzkyNzI3NTEsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiYzeyNWexM2It MmMzYS00ZGM0LWJjODgtZDc4ZDk1ZTljNzQ5IiwiY2xpZW50X2lkIjoiZmlyc3QtY2xpZW50In0.KhRIy7wOH2IsswDZ_AIXVFdtu6JZqtiLBZGZIypeNRw,\n expires_in=9,scope=custom_mod,\n jti=9e3 c46a4-02bf-4180-85e9-0ba93420ab88}]

\n
\n\n

当我解码以访问令牌 jwt 时,结果如下。

\n\n
{\n"aud": [\n"oauth2-resource"\n],\n"user_name": "dg",\n"scope": [\n"custom_mod"\n],\n"exp": 1579272741,\n"authorities": [\n"ROLE_ADMIN"\n],\n"jti": "9e3c46a4-02bf-4180-85e9-0ba93420ab88",\n"client_id": "first-client"\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我想,我缺少一些在网关服务器或 oauth 服务器中实现的部分,但我找不到。因为当我尝试使用 okta 而不是我的自定义身份验证服务器时,没有错误。

\n\n

网关应用程序.properties

\n\n
server.port=8081\nspring.security.oauth2.client.registration.gateway.client-id=first-client\nspring.security.oauth2.client.registration.gateway.client-secret=noonewilleverguess\nspring.security.oauth2.client.registration.gateway.authorization-grant-type=authorization_code\nspring.security.oauth2.client.registration.gateway.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}\n\nspring.security.oauth2.client.provider.gateway.authorization-uri=http://localhost:8094/oauth/authorize\nspring.security.oauth2.client.provider.gateway.token-uri=http://localhost:8094/oauth/token?scope=custom_mod\nspring.security.oauth2.client.provider.gateway.user-info-uri=http://localhost:8094/userinfo\nspring.security.oauth2.client.provider.gateway.user-name-attribute=name\n\nlogging.level.root=trace\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是屏幕错误消息:

\n\n
\n

1 月 17 日星期五 17:28:11 EET 2020 …

spring-security spring-security-oauth2 spring-cloud spring-oauth2 spring-cloud-gateway

1
推荐指数
1
解决办法
4749
查看次数

如何在 Spring Cloud Gateway .yml 配置中禁用全局 CORS 配置以允许来自任何来源的请求?

我想为我的微服务应用程序创建一个网关服务,并添加 spring 云网关文档中提到的配置以禁用网关中的 CORS:

spring:
  # GATEWAY CONFIG
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods: "*"
Run Code Online (Sandbox Code Playgroud)

但我仍然收到 403 Forbidden Error。我的配置错了吗?

java spring spring-boot spring-cloud spring-cloud-gateway

1
推荐指数
1
解决办法
2750
查看次数

jooq 在极少数情况下生成不正确的 sql

我有一个 Spring Cloud Gateway 应用程序将身份验证数据保存到数据库。应用程序在 kubernetes 中运行。我有太多不同的情况,有时我有 json 数据要保存,有时 json 数据为空。保存此数据的代码如下所示:

    with(AUTHENTICATED_SESSION) {
        context.insertInto(this, ACCESS_TOKEN_MD5_HASH, REFRESH_TOKEN, CONTEXT_DATA)
            .values(
                accessTokenMd5,
                refreshToken,
                if (contextData != null) {
                    JSONB.jsonb(objectMapper.writeValueAsString(contextData))
                } else {
                    null
                }
            )
            .execute()
    }
Run Code Online (Sandbox Code Playgroud)

生成的列定义

public final TableField<AuthenticatedSessionRecord, JSONB> CONTEXT_DATA = createField(DSL.name("context_data"), SQLDataType.JSONB, this, "");
Run Code Online (Sandbox Code Playgroud)

保存空值通常应该像这样:

insert into "public"."authenticated_session" ("access_token_md5_hash", "refresh_token", "context_data") values (?, ?, cast(? as jsonb))
    : -> with bind values      : insert into "public"."authenticated_session" ("access_token_md5_hash", "refresh_token", "context_data") values ('hash', 'token', cast(null as jsonb))
Run Code Online (Sandbox Code Playgroud)

有时查询看起来像这样,它会导致下面的异常

insert into "public"."authenticated_session" …
Run Code Online (Sandbox Code Playgroud)

postgresql jooq kotlin spring-boot spring-cloud-gateway

1
推荐指数
1
解决办法
522
查看次数

如何在Spring云网关(Webflux)后置过滤器中获取原始响应正文

我在 Spring Cloud Gateway 中实现了 Post 过滤器。但在将其发送到 UI 之前,我需要可读的格式(响应正文的 JSON 格式)。我正在获取 Exchange.getResponse()。(当我在控制台中打印时:)org.springframework.http.server.reactive.ReactorServerHttpResponse@3891d61a但它位于反应对象中。我无法看到从 API 到后置过滤器的实际原始响应。我搜索了许多 stackoverflow 主题,但找不到实际的解决方案。请协助...

java global-filter spring-boot spring-cloud-gateway

1
推荐指数
1
解决办法
1万
查看次数

Feign Client 与 Spring Cloud GatewayFilter 导致循环依赖

在某些检查期间,我需要向网关过滤器中的微服务发出请求。\n当我在 GatewayFilter(my SecurityFilter.java) 类中定义 Feign 类时,会出现以下错误。\n我该如何解决这种情况。

\n

错误:

\n
Description:\n\nThe dependencies of some of the beans in the application context form a cycle:\n\n\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n|  securityFilter defined in file [/target/classes/com/example/SecurityFilter.class]\n\xe2\x86\x91     \xe2\x86\x93\n|  cachedCompositeRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]\n\xe2\x86\x91     \xe2\x86\x93\n|  routeDefinitionRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x98\n\n\nAction:\n\nDespite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.\n
Run Code Online (Sandbox Code Playgroud)\n

网关过滤器类

\n
@Component\npublic class SecurityFilter implements GatewayFilterFactory<SecurityFilter.Config> {\n\n    private final UserApi userApi;\n\n    public SecurityFilter(UserApi …
Run Code Online (Sandbox Code Playgroud)

spring-security spring-boot spring-cloud-feign spring-cloud-gateway openfeign

1
推荐指数
1
解决办法
1792
查看次数

如何将 Spring MVC 应用程序与具有 OAuth2.0 安全性的 Spring Cloud Gateway 集成?

我有一个 Spring Boot MVC + Thymeleaf 应用程序,它通过 Spring Cloud Gateway 与一堆微服务进行通信。

mvc_app -> gateway -> (service_a, service_b,...)

现在,我想实现基于 OAuth 2 的安全性,并且希望将身份验证过程集中在网关级别。

这意味着:

  1. 如果用户尝试通过网关访问任何资源服务器(service_a、service_b 等)上的安全资源,网关应将用户重定向到 IdP 登录页面。
  2. 身份验证成功后,网关应使用 accessToken 来访问受保护的资源。

这可以通过以下方式实现:

  1. spring-boot-starter-oauth2-client使用适当的提供者/客户端配置将网关设置为 OAuth 2 客户端
  2. 使用TokenRelay过滤器将AccessToken转发到下游resource_servers。

问题:

当您通过网关进行身份验证时,身份验证状态将在网关应用程序级别维护。网关成功验证后,如何发回 AccessToken、IdToken 以便mvc_app进一步请求时使用相同的 AccessToken?

spring-security oauth-2.0 spring-boot spring-cloud-gateway

1
推荐指数
1
解决办法
421
查看次数

Spring Cloud API Gateway:Resilience4j:无法找到名为 CircuitBreaker 的 GatewayFilterFactory

我正在尝试使用 Spring Cloud Resilience4j 在我的云网关上实现断路器,但出现“无法找到名称为 CircuitBreaker 的 GatewayFilterFactory ”错误。

我正在使用的依赖项

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

春云版本:

<spring-cloud.version>2021.0.0</spring-cloud.version>
Run Code Online (Sandbox Code Playgroud)

主班

@SpringBootApplication
@EnableEurekaClient
public class CloudGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(CloudGatewayApplication.class, args);
    }

}
Run Code Online (Sandbox Code Playgroud)

application.yml配置

spring:
  application:
    name: CLOUD-GATEWAY
  cloud:
    gateway:
      routes:
        - id: USER-SERVICE
          uri: lb://USER-SERVICE
          predicates:
            - Path=/users/**
          filters:
            - name: CircuitBreaker
              args:
                name: userCircuitBreaker
                fallbackuri: forward:/userServiceFallBack
        - id: DEPARTMENT-SERVICE
          uri: lb://DEPARTMENT-SERVICE
          predicates:
            - Path=/departments/**
          filters:
            - …
Run Code Online (Sandbox Code Playgroud)

java circuit-breaker spring-boot spring-cloud-gateway resilience4j

0
推荐指数
1
解决办法
1534
查看次数