Forcing SSL for chosen controllers

Sooner or later you will have to include encrypted communication in your software. Today most sites merely use it for login purposes in order to submit the username and password in a secure way. This prevents eavesdroppers from sniffing them, even in a public wireless LAN. However, it is still possible to take over a session in a public WLAN, after the login. In order to prevent this, the full application must run with an SSL encryption. However, this will increase your system load.

The source code of the example is available at examples/chapter7/ssl/example-app.

Getting ready

You should have a configured Play application and followed the steps at: http://www.playframework.org/documentation/1.1.1/releasenotes-1.1#https.

Ensure that you can access your application at https://localhost:9443/ as well as http://localhost:9000. The next step is to force a login controller to be always SSL.

How to do it...

Create a controller with a @Before annotation, which checks whether the request is actually SSL encrypted:

public class EnsureSSL extends Controller { 
    @Before 
    static void sslOrRedirect() { 
        if(!request.secure) { 
            redirect("https://" + request.host + request.url); 
        } 
    } 
}

Now you can add this controller via the @With annotation to any other controller and make sure cleartext requests are redirected to SSL:

@With(EnsureSSL.class) 
public class Registration extends Controller {
   ...
}

How it works...

As you can see there is almost no logic in the preceding code. You can check if it works by trying to access your controller via HTTP:

> curl -v www.test.local/login
* Connected to www.test.local (192.168.0.7) port 80 (#0)
> GET /login HTTP/1.1
>
< HTTP/1.1 302 Found
< Location: https://www.test.local/login

You should however always keep in mind, that it is useless to redirect a POST request from a cleartext to an encrypted connection, which already includes all the sensitive data. So just make sure that the redirection happens before the transmission of data. Use a sniffer like Wireshark or TCPDUMP if you are not sure about your current implementation. However, you should be able to understand what happens in your application anyway.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.213.212