【问题标题】:Insert a custom Filter in the Spring Security Filter Chain in Spring Cloud Gateway在 Spring Cloud Gateway 的 Spring Security 过滤器链中插入自定义过滤器
【发布时间】:2020-11-04 05:49:28
【问题描述】:

我正在开发 Spring Cloud Gateway,它借助 Spring Security 过滤器链通过 OAuth2 进行身份验证。目前我在 OAuth2 的登录页面出现错误,因为我需要解决一些未知的授权请求未找到错误。我通过添加自定义位置标头并在发生异常时将用户路由到该位置找到了解决方法。目前,我在控制弹簧安全过滤器链之前面临挑战。以下是我使用的代码块:

 @Bean
 @Order(1)
 SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity serverHttpSecurity)
  throws Exception {
        ServerRequestCache requestCache = NoOpServerRequestCache.getInstance();
        WebFilter webFilter = new CustomWebFilter();
        serverHttpSecurity
          //.addFilterAt(webFilter, SecurityWebFiltersOrder.FIRST)
          .cors().and().headers()
          .frameOptions().disable()
          .and().requestCache().requestCache(requestCache)
          .and().csrf().disable()
          .authorizeExchange().pathMatchers("/**").authenticated()
          .and().oauth2Login()
          .and().oauth2Client()
          .and().oauth2ResourceServer().jwt();
     return serverHttpSecurity.build();
   }

这里我尝试在身份验证之前添加过滤器,但它阻止了请求,我得到一个空响应,它没有将我路由到登录页面。

.addFilterAt(webFilter, SecurityWebFiltersOrder.FIRST)

下面是我的 customWebFilter,我在其中添加了添加位置标题的代码。

public class CustomWebFilter implements WebFilter {

    @Autowired
    URIconfig uRIconfig;
    final Logger logger = LoggerFactory.getLogger(CustomWebFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
      URI location = exchange.getRequest().getURI();
      uRIconfig.setLocation(location);
      logger.info("Custom Pre Filter executed");
       return chain.filter(exchange);
    }
 }

在请求重定向到 OAuth2 登录页面之前,有人可以帮我添加标头或 cookie 吗?或者如何使用过滤器?

非常感谢任何帮助。提前致谢!

【问题讨论】:

    标签: spring-boot spring-security spring-security-oauth2 spring-cloud-gateway spring-filter


    【解决方案1】:

    我通过将弹簧安全过滤器链的顺序更改为 5 并在我的自定义过滤器中添加了一个 @Order(Ordered.HIGHEST_PRECEDENCE) 解决了这个问题。现在我的过滤器在我的 keycloak 登录页面之前调用,我可以添加我的自定义实现。以下是我所做的更改:

    Application.yml

    spring:
      security:
        filter:
          order: 5
    

    CustomWebFilter.java

    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Slf4j
    public class CustomWebFilter implements WebFilter {
    
      @Override
      public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        log.info("My Custom Web Filter.");
        return chain.filter(exchange);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-23
      • 2014-07-28
      • 2019-12-25
      • 2016-03-08
      • 2018-06-21
      • 2020-05-31
      • 2019-10-07
      • 2013-07-22
      • 2023-03-04
      相关资源
      最近更新 更多