Spring云网关版本:4.1.0
我正在尝试开发一个全局预过滤器,用于拦截传入的登录请求,并在用户已登录的情况下使用重定向重定向到登录页面。 为此,我开发了一个自定义预过滤器,它将响应状态代码更新为自定义状态 302 (HttpStatus.FOUND) 和位置标头,其中着陆页 URL 如下:
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// check if request is for login and user session is valid
ServerHttpResponse response = exchange.getResponse();
boolean updateStatus = response.setStatusCode(HttpStatus.FOUND);
log.debug("Response status code update: {}", updateStatus);
log.debug("Updated response status code: {}", response.getStatusCode());
response.getHeaders().add(HttpHeaders.LOCATION, "<landingPageUrl> here");
return response.setComplete();
}
Spring Cloud Gateway应用程序成功启动后,我登录了该网站,然后尝试再次访问登录页面。 但浏览器没有执行重定向,因为返回到浏览器的响应状态代码是 200 而不是 302。似乎自定义状态代码以某种方式被覆盖。 注意: Location 标头已正确更新并返回到浏览器。
我尝试解决该问题并检查日志,发现以下由上述代码编写的日志文件:
响应状态码更新:true 更新的响应状态代码:302 FOUND
我现在不知道响应状态在请求流中的哪一点被覆盖。
我还阅读了 Spring Cloud Gateway 提供的内置 RedirectTo 网关过滤器,但是我只需要通过代码更新状态代码。 https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway/gatewayfilter-factories/redirectto-factory.html
甚至我浏览了RedirectTo Gateway过滤器的代码,发现它也有类似的代码实现。 https://github.com/spring-cloud/spring-cloud-gateway/blob/main/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/factory/RedirectToGatewayFilterFactory .java
PS:我已经浏览过文章,但没有一篇对我有用: Spring Cloud Gateway:在自定义谓词中设置响应状态代码 Spring Cloud Gateway变更响应
请帮忙通过代码设置自定义状态302响应并返回浏览器执行重定向。
你找到解决方案了吗,我对答案很感兴趣 真诚的