Reputation: 861
Gorilla sessions work quite well by storing session data in encrypted form in cookie.
But is it possible to use localStorage instead of cookie jar. Endpoints will return JSON with property session
. Frontend code will save session
in localStorage.
When endpoint would be queried then session
would be passed in header.
I can encrypt/decrypt/sign/verify session with https://github.com/gorilla/securecookie
I wonder if it is possible to use localStorage instead of cookie the way I described? (I expect yes but may be there is reason to not do so)
If yes does such solution already exists?
If you wonder "why?" I wish to handle session explicitly. Cookies are not always stored when web services on different domains are queried.
Upvotes: 2
Views: 961
Reputation: 2134
First of all, yes it is possible.
Second of all, it is very easy to do.
All you essentially need to do is pas the 'cookie' into the local storage on the front end, but rather than using the back end to store the session into a cookie, pass it back via an endpoint to JavaScript.
So here's what I was thinking of kinda doing, I mean I'm just using pseudo code here because I've never even bothered using Go before. The JavaScript is somewhat more implemented as I've has plenty of experiences with JavaScript, but you may wish to change it, who knows?
@GET
@Path("/getsession")
getSession () { return session; }
@POST
@Path("/setsession")
setSession (json) { session = validateSession(json); }
$.ajax(
url:"/getsession",
type: "GET",
success: function (data) {
var session = JSON.stringify(data);
localStorage.setItem("session", session);
}
);
var storedSession = localStorage.getItem("session");
if (storedSession != null) {
storedSession = JSON.parse(storedSession);
$.ajax(
url:"/setsession",
type: "POST",
data: storedSession,
success: function () {
console.log("success!");
}
);
}
Upvotes: 4