Skip to content Skip to sidebar Skip to footer

How To Read Flask Sessions Using Javascript?

I have a secured flask session session = 'xC4tHoSZQVSHpVtnHUONYb/obAA=?USER_TOKEN=UycuZUp3Rndja1JnREFJQU1CZThwWVpqbkRWNHZpQW9QMlg0TzY5ZXN4MU5rTlZOaEM5RERuczBCRkRqSHFDY0YxTGZMSUM3Wl

Solution 1:

I could be completely contradicted on this, but I've been of the understanding that you can't access the session data with Javascript because of some of the internals that the Werkzeug secure cookie module uses. I've got plans to try out this snippet as a workaround:

http://flask.pocoo.org/snippets/51/

But until I get a chance to try it I wouldn't know whether or not it could do some of the things lacking with the basic session module of Flask.

Solution 2:

Since the question was asked Flask switched to itsdangerous client side sessions by default.

As this is still the top google result for this question and i had some problems figuring it out myself, here is how to do it nowadays:

functionparse_session(){
    var cookie = Cookies('session');
    if(! cookie) return;
    // Is the content ziped ?var un_64 = "";
    if(cookie[0] == "."){
        var data = cookie.split('.')[1].replace(/_/g, '/').replace(/-/g, '+');
        un_b64 = atob(data);
        un_b64 = pako.inflate(un_b64, {to: 'string'});
    }else{
        var data = cookie.split('.')[0].replace(/_/g, '/').replace(/-/g, '+');
        un_b64 = atob(data);
    }
    return jQuery.parseJSON(un_b64);
}

This snippet uses jquery, cookie.js and paco (to unzip). Flasks 'SESSION_COOKIE_HTTPONLY' config variable need to be set to False to be able to read the session on the client side.

Solution 3:

Alright. for accessing the cookie session which is set by the flask. we can't directly access in js using document.cookies as it HttpOnly. However, you can access it using the template engine syntax.

let session = {{session|tojson}};

Post a Comment for "How To Read Flask Sessions Using Javascript?"