Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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