Created
November 14, 2017 10:07
-
-
Save samuelstein/4d9ce4de7336a521bd36dc97b21b49a1 to your computer and use it in GitHub Desktop.
HTTPS Redirect filter for play framework (>=2.5)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package utils.filters; | |
import akka.stream.Materializer; | |
import play.Configuration; | |
import play.mvc.Filter; | |
import play.mvc.Http; | |
import play.mvc.Result; | |
import javax.inject.Inject; | |
import java.util.concurrent.CompletionStage; | |
import java.util.function.Function; | |
import static play.mvc.Results.movedPermanently; | |
//Note that we create a Filter implementation and not an EssentialFilter one because we do not care about the body | |
//tested with play framework 2.5 | |
public class HTTPSRedirectFilter extends Filter { | |
private boolean httpsRedirect; | |
private int sslPort; | |
@Inject | |
public HTTPSRedirectFilter(Materializer mat, Configuration configuration) { | |
super(mat); | |
httpsRedirect = configuration.getBoolean("httpsRedirect", false); | |
sslPort = configuration.getInt("https.port", 443); | |
} | |
@Override | |
public CompletionStage<Result> apply(Function<Http.RequestHeader, CompletionStage<Result>> nextFilter, Http.RequestHeader rh) { | |
if (httpsRedirect) { | |
return nextFilter.apply(rh).thenApply(result -> { | |
if (!rh.secure()) { | |
return movedPermanently("https://" + rh.host() + ":" + sslPort + rh.uri()); | |
} else { | |
return result.withHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains"); | |
} | |
}); | |
} else { | |
return nextFilter.apply(rh); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment