我有一个Java Play!作为RESTful API的Heroku上的应用程序。我想对所有客户端连接强制执行HTTP over TLS。这样做的最佳做法是什么?
答案 0 :(得分:1)
最短的代码是拦截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()));
}
};
}
}
或使用动作合成(对选择“明智的”网络服务很有用)
在新的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 {