我尝试使用 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 进行了空检查。没有这个,它仍然有效,但 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/