How to read the Play session from AngularJS
Contents
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:
|
|