我有一个 Java Play! Heroku 上用作 RESTful API 的应用程序。我想对所有客户端连接强制执行 HTTP over TLS。这样做的最佳做法是什么?
最佳答案
最短的代码是在Global.java
中拦截请求
@Override
public Action onRequest(final Http.Request request, Method actionMethod) {
//contains http or https
String header=request.getHeader("x-forwarded-proto");
if(header != null && header.equals("http")){
return new Action.Simple() {
@Override
public F.Promise<Result> call(Http.Context ctx) throws Throwable {
return F.Promise.pure(redirect("https://" + request.host() + request.path()));
}
};
}
}
或使用 Action 组合(对选择“明智的”网络服务很有用)
在新的 ForceHttps.java
中:
package actions;
import play.Play;
import play.libs.F;
import play.mvc.*;
public class ForceHttps extends Action<Controller> {
// heroku header
private static final String SSL_HEADER = "x-forwarded-proto";
@Override
public F.Promise<SimpleResult> call(Http.Context ctx) throws Throwable {
if (Play.isProd() && !isHttpsRequest( ctx.request() )) {
return F.Promise.promise(() -> redirect("https://" + ctx.request().host() + ctx.request().uri()) );
}
// let request proceed
return this.delegate.call(ctx);
}
private static boolean isHttpsRequest(Http.Request request) {
// heroku passes header on
return request.getHeader(SSL_HEADER) != null && request.getHeader(SSL_HEADER).contains("https");
}
}
在您的 Application.java
中(或在任何类/方法之前):
@With(ForceHttps.class)
public class Application extends Controller {
关于ssl - 如何为 java Play 强制执行 https! Heroku 上的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26954324/