ssl – 如何在Heroku上强制使用HTTPS进行Spring Boot应用程序?

我尝试使用FORCE_HTTPS = true和SECURITY_REQUIRE_SSL = true作为配置变量,但都不起作用.我知道前者是由Cloud Foundry支持的,但我已经向Heroku确认他们不支持它. Spring Boot支持SECURITY_REQUIRE_SSL属性,但可能仅适用于基本身份验证?
最佳答案
我能够通过创建HttpEnforcer过滤器来解决这个问题:

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HttpsEnforcer implements Filter {

    private FilterConfig filterConfig;

    public static final String X_FORWARDED_PROTO = "x-forwarded-proto";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

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

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (request.getHeader(X_FORWARDED_PROTO) != null) {
            if (request.getHeader(X_FORWARDED_PROTO).indexOf("https") != 0) {
                String pathInfo = (request.getPathInfo() != null) ? request.getPathInfo() : "";
                response.sendRedirect("https://" + request.getServerName() + pathInfo);
                return;
            }
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // nothing
    }
}

并在现有的@Configuration类中注册它.

@Bean
public Filter httpsEnforcerFilter(){
    return new HttpsEnforcer();
}

这与我在上面的注释中发布的解决方案不同,因为对pathInfo进行了空检查.没有它,它仍然有效,但位置确实在最后显示为null.

$curl -i http://www.21-points.com
HTTP/1.1 302 Found
Server: Cowboy
Connection: keep-alive
Expires: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
X-Xss-Protection: 1; mode=block
Pragma: no-cache
Location: https://www.21-points.comnull
Date: Tue, 31 Oct 2017 14:33:26 GMT
X-Content-Type-Options: nosniff
Content-Length: 0
Via: 1.1 vegur

转载注明原文:ssl – 如何在Heroku上强制使用HTTPS进行Spring Boot应用程序? - 代码日志