首页 文章

Zuul代理oAuth2在Spring Boot中未经授权

提问于
浏览
1

我有一个使用oAuth2保护的微服务,称为country-service . 当我直接向包含我的JWT持票人令牌的服务发送请求时,一切正常:

enter image description here

server:
  port: 8081

spring:
  database:
    driverClassName: org.postgresql.Driver
  datasource:
    url: jdbc:postgresql://localhost:5432/vue-boot-country
    username: postgres
    password: postgres
  jpa:
    hibernate:
      ddl-auto: validate
    database-platform: org.hibernate.dialect.PostgreSQLDialect

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

我也有一个api-gateway(Zuul代理):

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class VueBootApiGatewayApplication {

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

没有其他文件比这两个

server:
  port: 8765

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

zuul:
  routes:
    vue-boot-country-service: /api/country/**
  add-proxy-headers: true

我无法向代理发送成功的请求,我一直收到“未经授权”的错误:

enter image description here

注意:当我从资源服务器中删除oAuth2安全性时,Zuul代理似乎可以工作 .

有人知道我在做错了吗?

1 回答

  • 4

    这与zuuls所谓的“敏感” Headers 有关,比如“授权” . 对于传递给内部的所有请求,这些都被过滤了......

    我不知道,如果设置标头已经在使用此配置:

    zuul:
      ignoredHeaders:
        - authorization
    

    如果没有,您可以定义一个Zuul过滤器bean来手动管理它:

    @Component
    public class RelayTokenFilter extends ZuulFilter{
        @Override
        public String filterType() {
            return "pre";
        }
    
        @Override
        public int filterOrder() {
            return 10000;
        }
    
        @Override
        public boolean shouldFilter() {
            return true;
        }
    
        @Override
        public Object run() {
            RequestContext context = RequestContext.getCurrentContext();
    
            @SuppressWarnings("unchecked") Set<String> ignoredHeaders = (Set<String>) context.get("ignoredHeaders");
            ignoredHeaders.remove("authorization");
    
            return null;
        }
    }
    

相关问题