如何使用自动证书管理在 Heroku 上强制使用 Jetty Embedded HTTPS
How to force HTTPS with Jetty Embedded on Heroku with Automated Certificate Management
我有一个使用 Jetty Embedded 运行 在 Heroku 环境中用 Java 编写的 REST 应用程序。我想强制所有流量都通过 HTTPS。关于如何实现这一点有一些很好的答案,例如 this one and . However, all answers require the TLS/SSL certificate to be read from a file. I would like to use Heroku's Automated Certificate Management (details here) 以避免每年在证书过期时更新证书。使用ACM意味着我无权访问证书文件。
有什么方法可以配置 Jetty 以在不从文件中读取证书的情况下强制使用 HTTPS,或者以某种方式仍然能够使用 Heroku ACM?
您可以使用实现 doFilter
的 servlet 过滤器来执行此操作,如下所示:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
String protocol = req.getHeader("X-Forwarded-Proto");
if (protocol.equals("http")) {
String url = "https://" + req.getServerName() + req.getContextPath() + req.getServletPath();
if (req.getPathInfo() != null) {
url += req.getPathInfo();
}
System.out.println("Forwarding request to: " + url);
resp.sendRedirect(url);
} else {
System.out.println("Not forwarding protocol: " + protocol);
chain.doFilter(request, response);
}
}
这里是a complete example using Tomcat,但是原理是一样的
我有一个使用 Jetty Embedded 运行 在 Heroku 环境中用 Java 编写的 REST 应用程序。我想强制所有流量都通过 HTTPS。关于如何实现这一点有一些很好的答案,例如 this one and
有什么方法可以配置 Jetty 以在不从文件中读取证书的情况下强制使用 HTTPS,或者以某种方式仍然能够使用 Heroku ACM?
您可以使用实现 doFilter
的 servlet 过滤器来执行此操作,如下所示:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
String protocol = req.getHeader("X-Forwarded-Proto");
if (protocol.equals("http")) {
String url = "https://" + req.getServerName() + req.getContextPath() + req.getServletPath();
if (req.getPathInfo() != null) {
url += req.getPathInfo();
}
System.out.println("Forwarding request to: " + url);
resp.sendRedirect(url);
} else {
System.out.println("Not forwarding protocol: " + protocol);
chain.doFilter(request, response);
}
}
这里是a complete example using Tomcat,但是原理是一样的