首页 文章

在Zuul代理后面的Spring重定向url问题

提问于
浏览
8

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

基于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

这是一个错误,还是预期的行为?我认为使用“redirect:”是为了纪念从代理传递的前向头 .

2 回答

  • 1

    如您所见RedirectView忽略 X-FORWARDED-* Headers . 简单地说,你不能使用“ redirect:/account" .

    而是实例化 RedirectView 并相应地配置它:

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

    由于Spring Framework 4.3(目前为RC1)setHosts方法可用 .

  • 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
    

相关问题