Search code examples
pythonflaskbrowserflask-socketiobidirectional

Bidirectional Communication without cookies and sid in URL in flask


I am trying to find a way to establish a bidirectional communication for a Server-Client architecture without using cookies and without the sessionId being send in the URL. Flask-SocketIO e.g. unfortunately does both.

Maybe there is a way to send the sessionID as a POST?

Any help would be awesome.


Solution

  • You can use other storage in the browser to store the session ID. For example, you can use LocalStorage. To use LocalStorage is quite simple, and the following example from MDN should explain the usage clearly

    localStorage = window.localStorage;
    localStorage.setItem('myCat', 'Tom');
    var cat = localStorage.getItem('myCat');
    localStorage.removeItem('myCat');
    // clear all items
    localStorage.clear();
    

    and every other thing should be normal as long as you use JavaScript to manually send the session ID to the flask server.

    To send the session ID to the browser for the first time the user login, you can include it in the response header or in the meta tag of the webpage and let your JavaScript to retrieve it and store it.

    To let Flask-login stop sending the session ID in the cookie and send them in meta instead, you have to write your own session interface. Fortunately, the Flask's code is pretty clear and you can refer it to create your own. Just inherent SessionInterface and implement your save_session and open_session methods. after you are done you can use app.session_interface = YourSessionInterface() to switch Flask's session engine to yours and then init your LoginManager and other stuff. Hope this will give you some thought.