Wednesday, October 30, 2013

Password-protect Play2 Framework Webapp

There are numerous extensions to bring authentication and access control to your Play based website. For example the Deadbolt 2 authorization system lets you define access rights per controller and method. Or you can roll your own, as this step by step guide shows.

What to do if you just want basic http authentication for the whole site? As of today there's no such thing built in. (If this changes, let me know...)

If you're serving your Play pages through Apache as reverse proxy, you're lucky.

Going through a reverse proxy is a good idea anyway:
  • You get the option for load balancing and failover: run multiple instances.
  •  Run multiple Play sites on the same machine, on whatever port number, and expose them all on port 80 to the outside.
 Your apache website definition looks simething like this:
<VirtualHost *:80>
  ServerName my-play-app.example.com
  ProxyPreserveHost on
  <Location />
    ProxyPass http://192.168.56.100:9000/ connectiontimeout=9999999 timeout=9999999
    ProxyPassReverse http://192.168.56.100:9000/

    AuthType Basic
    AuthName "whatever" 
    AuthUserFile /etc/apache2/sites-available/.htpasswd-mysite
    Require valid-user
  </Location>
</VirtualHost>
I'm running my Play app in a virtual machine (192.168.56.100) on standard port 9000. The connection timeout is there so that long running tasks are not aborted by the proxy.

Create the password file as usual:
cd /etc/apache2/sites-available/
htpasswd -c .htpasswd-mysite newuser

And then refresh Apache, and you're done:
service apache2 reload


No comments:

Post a Comment