Sharing Session Information between WordPress and Grails using Cookies and base64 encoding

03 / Aug / 2010 by Vivek Krishna 0 comments

A scenario arose in one of our projects that we had to share some information between the grails application (which was taking care of dynamic content) and wordpress (which was used to maintain the static pages about the application). The information was the logged in user’s name so that we could display that on the header. After giving it some thought, we decided that setting a cookie with the logged in user’s name from the grails application and then reading it from the wordpress application using javascript was one way of doing so.

This was achieved by setting the cookie with code on grails side as

Cookie cookie = new Cookie('userNameCookie', fullname);
cookie.setVersion(-1)  // unknown version bypasses quoting logic
cookie.path = "/"
cookie.maxAge = 30 * 60 * 60; //30 minutes life
response.addCookie(cookie)

There is an excellent jQuery cookie plugin to read cookies using javascript. All that needs to be done is include the javascript file and call the method given below to get the value from it

jQuery.cookie('userNameCookie')

However, there was an issue with this approach. The usernames could have unicode characters like ä, ö etc. The cookie was not getting set from the grails application and threw an Exception because the unicode characters weren’t escaped. The exception also suggested that we could use decodeBase64(). But since it was due to encode, we decided to convert the fullname to bytes, encode it to base64, call the toString() method and then set the value. What we did was to change the cookie value to from grails

Cookie cookie = new Cookie('usercookie', fullname.bytes.encodeBase64().toString());

In order to decode this base64 encoded string on the client side, we used the jQuery Base 64 Functions plugin. This can be used to decode a base64 encoded string as

jQuery.base64Decode(jQuery.cookie('userNameCookie'));

This worked like a charm.

Hope this helps

Vivek

vivek[at]intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a comment -