【问题标题】:Spring redirect url issue when behind Zuul proxy在 Zuul 代理后面时出现 Spring 重定向 url 问题
【发布时间】:2016-05-28 23:51:37
【问题描述】:

在过去的 2 天里,我一直试图找出一个奇怪的重定向问题,但没有成功。

基于spring-cloud示例项目,我已经配置了Eureka、Zuul和一个运行在Zuul后面的基础服务。

我有以下方法;

@RequestMapping(method = RequestMethod.POST, value = "/register")
public String registerDevice(Principal principal, String response) {
  // ...
  return "redirect:/account";
}

表单设置为发布到代理 URL,如下所示;

POST https://localhost:8443/service/register

(Zuul 在 localhost:8443 上运行)。

本地服务(非代理)的 URL 将是; http://localhost:9001/register

通过上述方法正确代理了POST调用,但是发送到浏览器的重定向位置是服务的非代理URL; http://localhost:9001/account

Zuul 代理肯定会发送正确的 x-forwarded-* 标头,因此我希望 Spring 中的视图解析器能够基于 x-forwarded 值构建正确的重定向。

为了证明标头发送正确,我重新配置了方法如下;

@RequestMapping(method = RequestMethod.POST, value = "/register")
public void registerDevice(Principal, String response, HttpServletResponse response) {
  // ...
  String rUrl = ServletUriComponentsBuilder.fromCurrentContextPath().path("/account").build().toUriString();
  servletResponse.sendRedirect(rUrl);
}

正确地将浏览器重定向到代理位置; https://localhost:8443/service/account

这是一个错误,还是预期的行为?我认为使用“重定向:”是为了尊重从代理传递的转发标头。

【问题讨论】:

  • 你找到解决方案了吗?

标签: spring-mvc spring-boot spring-cloud netflix-eureka netflix-zuul


【解决方案1】:

如您所见,RedirectView 忽略了 X-FORWARDED-* 标头。 简单来说就是不能用“redirect:/account"”。

而是实例化 RedirectView 并进行相应的配置:

RedirectView redirect = new RedirectView("account");
redirect.setHosts(new String[]{ request.getHeader("X-FORWARDED-HOST") });

自 Spring Framework 4.3(目前为 RC1)setHosts 方法可用。

【讨论】:

  • 我有同样的问题,在 RedirectView (v4.2.5) 的最新版本中没有看到 setHosts()
  • @damien-polegato 你是对的! setHosts 方法已在 Spring Framework 4.3 中添加。我更新了我的答案。谢谢。
  • 谢谢,如果您有任何线索,我的问题在这里也有同样的问题:stackoverflow.com/questions/36881835/…
【解决方案2】:

如果您在后端应用程序中使用 tomcat 作为嵌入式服务器,则可以使用以下设置(application.properties、yml 等):

server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto

或者更通用的方式:

server.use-forward-headers=true

【讨论】:

    猜你喜欢
    • 2017-04-24
    • 2019-01-18
    • 2017-09-03
    • 2011-11-10
    • 1970-01-01
    • 2015-11-28
    • 2021-07-04
    • 1970-01-01
    • 2017-06-12
    相关资源
    最近更新 更多