强制 spring 数据休息使用 https 方案

Force spring data rest to use https scheme

我在我的应用程序中使用 spring-data-rest,它位于从 HTTP 重定向到 HTTPS 的 apache 反向代理后面

这反过来会导致错误的 hrefs:http 而不是 https 方案。

示例:

{
  "_links" : {
    "profile" : {
      "href" : "http://my.host/api/profile"
    }
  }
}

有什么方法可以配置 spring.data.rest 强制使用 https 方案吗?

在深入挖掘源码后,我发现所有link的创作都源于此point,似乎无法在[=18=中配置强制使用https方案] 方法。

所以我创建了一个过滤器,将请求 URL 中的 http:// 替换为 https://,问题就解决了。这是片段:

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletRequestWrapper wrapped = new HttpServletRequestWrapper(request) {
            @Override
            public StringBuffer getRequestURL() {
                final StringBuffer originalUrl = ((HttpServletRequest) getRequest()).getRequestURL();
                final String updatedUrl = originalUrl.toString().replace("http://", "https://");
                return new StringBuffer(updatedUrl);
            }
        };
        filterChain.doFilter(wrapped, servletResponse);
    }

实际上,Spring Data Rest 使用支持来自代理请求的特殊 headers 的 HATEOAS,检查一下:

您要找的header是:X-Forwarded-Proto

我有点不确定但是。我做了以下操作,链接似乎有效。

server:
  forward-headers-strategy: NATIVE

我遇到了同样的问题,所有的答案都帮助我通过 2 个步骤找到了一个简单的解决方案:

  1. 我在 spring-data-rest v2.5.4 应用程序中添加了配置以使用 X-Forwarded-* headers

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.filter.ForwardedHeaderFilter;
    
    
    @Configuration()
    public class ApiConfiguration {
    
      @Bean()
      ForwardedHeaderFilter forwardedHeaderFilter() {
        return new ForwardedHeaderFilter();
      }
    }
    
  2. 我在我的代理 (nginx v1.20.0) 中添加了配置以转发 schemehostport

    location /api {
      proxy_pass       http://localhost:8080;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Forwarded-Host  $host;
      proxy_set_header X-Forwarded-Port  $server_port;
    }
    

希望对以后的朋友有所帮助