Forcing HTTPS in a Play 2 Scala app
At Process Street we've been developing a new app called MailTheme that, like the Process Street app, it uses the Play Framework.
Unlike Process Street, MailTheme will be running on Google Cloud and, for the time being, won't be behind a load balancer or proxy. As such, I needed to make all HTTP requests auto-redirect to HTTPS via Play. This turned out to be more difficult than I first imagined, as Play prior to version 2.3 has no way to detect whether or not the incoming request is over SSL.
Sure, you can look at the port, but that only works if the browser has sent the port, which it doesn't do for port 80 and 443. Moreover, Play inexplicably does not expose the protocol anywhere in the request object. This doesn't leave you with many options other than than upgrading to Play 2.3.
Fortunately, Play 2.3 provides a secure
property in the request object. With that in hand, we can now write a HttpsAction
that ensures an action is over HTTPS:
To use it in your app, simply add the code, and use it where you'd normally use an action, like so:
And there you have it. Keep in mind that I haven't tested this with any load balancers or proxies, so I don't know how it'll perform under those circumstances.