ssl - 如何为 java Play 强制执行 https! Heroku 上的应用程序?

标签 ssl heroku https playframework

我有一个 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/

相关文章:

ssl - Gitlab 致命 : unable to access '.......' SSL Certificate problem: unable to get issuer certificate

多个域的ssl证书,一个IP

android - 如何使用 FileInputStream --Android 打开 *.cer 文件

python - Heroku 未被识别为内部或外部命令 (Windows)

通过 ssh 克隆 Git,通过 https 推送

ssl - HTTPS 不适用于 SSL 证书

ssl - nginx 简单 SSL 连接

git - 在 Heroku 上克隆以前的版本

typescript - Heroku - fatal error : Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

asp.net - 如何在 visual studio 2013 中使用 SSL