我想在 Dropwizard 中将传入的 http 连接重定向到 https,最好在配置文件中切换(例如,使用 YAML 文件,就像其他连接属性一样)。 [我看过this question ,而且我有理由相信这不是解决方案]
我在 several 中找到的解决方案places涉及 Hook Filter检查架构,如果找到“http”,则使用修改后的 URL 调用 sendRedirect。这涉及对行为进行硬编码以使其始终发生。
如果我扩展 HttpConnectorFactory ,似乎我可以在 YAML 中添加配置以决定是否要进行重定向。但是,我不清楚在不破坏其他代码的情况下添加属性会有多复杂。
这似乎是一项常见的任务;有没有标准的“首选”方法来做到这一点?我希望 Dropwizard 有优雅的内置支持,like Jetty does ,但我找不到它。
最佳答案
我不知道有一个“首选”的方式来做到这一点,但这样的事情怎么样(对于 Dropwizard 0.7.0):
void addHttpsForward(ServletContextHandler handler) {
handler.addFilter(new FilterHolder(new Filter() {
public void init(FilterConfig filterConfig) throws ServletException {}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
StringBuffer uri = ((HttpServletRequest) request).getRequestURL();
if (uri.toString().startsWith("http://")) {
String location = "https://" + uri.substring("http://".length());
((HttpServletResponse) response).sendRedirect(location);
} else {
chain.doFilter(request, response);
}
}
public void destroy() {}
}), "/*", EnumSet.of(DispatcherType.REQUEST));
}
@Override
public void run(ExampleConfiguration configuration, Environment environment) throws Exception {
//...
if (configuration.forwardHttps()) {
addHttpsForward(environment.getApplicationContext());
}
//...
}
您只需在应用程序配置中添加一个 boolean 值,然后您就可以使用 YAML 轻松切换 https 转发。
关于java - 在 Dropwizard 中将 http 连接重定向到 https 的首选方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23902576/