Month: July 2013

Securing AngularJS Applications with Play


When you start migrating from classic page-reloading web applications, it can be quite confusing how to secure your JavaScript-driven app. Sure, you could keep using cookies, but cookies aren’t very secure, even more so if you allow them to be read from JavaScript.

James Ward from Typesafe wrote an excellent article about this topic, so I don’t want to repeat this here but instead encourage you to read his article first. In summary, the server generates an authentication token that our application uses to sign all requests by adding a custom HTTP header (X-AUTH-TOKEN for example).

He also shows how to implement this approach in “normal” JavaScript, jQuery and Play-Java. How is this done in AngularJS and Play-Scala? It’s actually pretty easy, let me show you how.

Signing Requests

In AngularJS we use the $http service to make AJAX-requests. $http’s provider (i.e. the module responsible for injecting the $http service), $httpProvider, offers us the possibility to define default headers. If you want to sign every request, you add them to the defaults.headers.common object. If you only want specific HTTP verbs, you can for example add the header to

$"/login", credentials).then(function(response) { $httpProvider.defaults.headers.common["X-AUTH-TOKEN"] = response.token; }); ▸