Enforce Https routing for login with play framework

后端 未结 6 2147
滥情空心
滥情空心 2020-12-05 03:22

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?

6条回答
  •  一个人的身影
    2020-12-05 03:29

    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;
                }
            }
        }    
    }
    

提交回复
热议问题