How to read the Play session from AngularJS

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:

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):

This gives you access to the $cookies service.

3. Decypher the cookie data

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

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:

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

4 Comments How to read the Play session from AngularJS

  1. Marius

    Is there a reason you prefer _.each over angular.forEach?

    And when you use the Play session cookie, doesn’t this make you vulnerable to CRSF attacks?

  2. Manuel

    Good point about CSRF, of course you should use appropriate mechanisms (token generation) – but that holds also true if the cookie is not exposed to javascript, does it not? About _.each against angular.forEach, there’s no particular reason I prefer it other than it being very short (_) and having already made use of underscore.js in the project (so I didn’t need to add it as an extra dependency).

  3. Phu

    We just create a different cookie and set the session id to the cookie’s values, this way the session cookie is still httpOnly and no need for parsing; later you can stamp the new cookie with something other than session id.

  4. Marius

    Small tip, use a cookie called XSRF formyour token, it makes the whole authorization stuff easier, because Angular picks it up automatically.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">