If you happen to work, like me, on a project that makes use of both the Play framework and AngularJS, you may at some point need to read some data from the Play session in your AngularJS application. Play uses a client-side session, which makes sharing the data with client-side applications easy.

In order to access the session data on the client-side, you’ll need the following:

1. Allow the Play session to be read by javascript

In application.conf, set the session.httpOnly flag to false:

1
2
# Allow the session cookie to be accessed from JavaScript libraries
session.httpOnly=false

2. Enable the $cookies service in AngularJS

You’ll need to use the ngCookies module (provided by angular-cookies.js - make sure you have loaded this file):

1
angular.module('myApp', ['ngCookies']);

This gives you access to the $cookies service.

Play encodes the session into a single string, so you’ll need to decode it:

1
2
3
4
5
6
7
8
9
// read Play session cookie
var rawCookie = $cookies['PLAY_SESSION'];
var rawData = rawCookie.substring(rawCookie.indexOf('-') + 1);
var session = {};
_.each(rawData.split("\u0000"), function(rawPair) {
    var pair = rawPair.split(':');
    session[pair[0]] = pair[1];
});
console.log(session);

The code above makes use of underscore.js, if you don’t use it yet, I can only recommend using it.

That’s it! You now can make the session data available throughout your Angular application, for example by providing a service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
angular.module('admin.services', ['ngCookies']).
    factory('session', ['$cookies', function($cookies) {
        // read Play session cookie
        var rawCookie = $cookies['PLAY_SESSION'];
        var rawData = rawCookie.substring(rawCookie.indexOf('-') + 1);
        var session = {};
        _.each(rawData.split("\u0000"), function(rawPair) {
            var pair = rawPair.split(':');
            session[pair[0]] = pair[1];
        });
        return session;
}]);

Update: for Play 2.1.3 and above, the cookie encoding changed, and is now:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
angular.module('admin.services', ['ngCookies']).
    factory('session', ['$cookies', function($cookies) {
        // read Play session cookie
        var rawCookie = $cookies['PLAY_SESSION'];
        var rawData = rawCookie.substring(rawCookie.indexOf('-') + 1, rawCookie.length -1);
        var session = {};
        _.each(rawData.split("&"), function(rawPair) {
            var pair = rawPair.split('=');
            session[pair[0]] = pair[1];
        });
        return session;
    }])