ssl - 如何为 Heroku 上的 Spring Boot 应用程序强制使用 HTTPS?

标签 ssl spring-boot heroku https

我尝试使用 FORCE_HTTPS=trueSECURITY_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 进行了空检查。没有这个,它仍然有效,但 Location 确实在末尾显示为 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 上的 Spring Boot 应用程序强制使用 HTTPS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46956877/

相关文章:

ruby-on-rails - 如何推送 heroku master?

python-2.7 - SSL(缩进错误)使用 virtualenvwrapper (_lib.SSL_ST_INIT)

ssl - 使用 SSL 和 NGINX 作为反向代理配置 Sonarqube - 错误代码 : SSL_ERROR_RX_RECORD_TOO_LONG

java - 可能考虑使用较短的maxLifetime值——hikari连接池spring boot

spring - BCryptPasswordEncoder - 编码密码看起来不像 BCrypt

ruby - Heroku Rails 应用 Assets 管理

heroku - 基于 Heroku 建议的云微服务设计

node.js - 使用 SSL 托管多个 node.js 站点

java - 添加另一个 SSL 连接

java - Spring Boot 是否支持服务器名称指示(SNI)?