Skip to content

Instantly share code, notes, and snippets.

@samuelstein
Created November 14, 2017 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelstein/4d9ce4de7336a521bd36dc97b21b49a1 to your computer and use it in GitHub Desktop.
Save samuelstein/4d9ce4de7336a521bd36dc97b21b49a1 to your computer and use it in GitHub Desktop.
HTTPS Redirect filter for play framework (>=2.5)
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