Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce Https routing for login with play framework

Tags:

I want to enforce https routing for the login page only of my application.

Is it possible to do so with Play! without the use of a front end http server?

like image 253
emt14 Avatar asked Sep 14 '11 10:09

emt14


1 Answers

You can use an @Before interceptor to redirect every request, even if the user types http:// directly. Below is the code that I use (it works when running containerless play run, or when running behind a front end such as on Heroku).

public class HttpsRequired extends Controller {     /** Called before every request to ensure that HTTPS is used. */     @Before     public static void redirectToHttps() {         //if it's not secure, but Heroku has already done the SSL processing then it might actually be secure after all         if (!request.secure && request.headers.get("x-forwarded-proto") != null) {             request.secure = request.headers.get("x-forwarded-proto").values.contains("https");         }          //redirect if it's not secure         if (!request.secure) {             String url = redirectHostHttps() + request.url;             System.out.println("Redirecting to secure: " + url);             redirect(url);         }     }      /** Renames the host to be https://, handles both Heroku and local testing. */     @Util     public static String redirectHostHttps() {         if (Play.id.equals("dev")) {             String[] pieces = request.host.split(":");             String httpsPort = (String) Play.configuration.get("https.port");             return "https://" + pieces[0] + ":" + httpsPort;          } else {             if (request.host.endsWith("domain.com")) {                 return "https://secure.domain.com";             } else {                 return "https://" + request.host;             }         }     }     } 
like image 123
Ned Twigg Avatar answered Sep 30 '22 04:09

Ned Twigg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!