Search code examples
goauthenticationsessionsession-cookiesgorilla

Gorilla Session - Session per User


When using gorilla sessions, every example I have seen does some variant of the following:

    var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))

    func MyHandler(w http.ResponseWriter, r *http.Request) {
        // Get a session. We're ignoring the error resulted from decoding an
        // existing session: Get() always returns a session, even if empty.
        session, _ := store.Get(r, "session-name")
        // Set some session values.
        session.Values["foo"] = "bar"
        session.Values[42] = 43
        // Save it before we write to the response/return from the handler.
        err := session.Save(r, w)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    }

I have done this as well in my code, and it works. What I am confused about is session, _ := store.Get(r, "session-name"). It is a hard coded value which will always retrieve the same session.

To verify this I had 2 incognito browsers create a session with the ID of the user as a value within the session's value map. Both browsers returned the values of the last user to create the session. This all makes sense to me since we're using the same session name for everything.

My question is the following To get a session per authenticated user, do I need to dynamically set the session name myself (probably with some info from the authenticated user itself)? If so, how would I be able to retrieve that information when the user accesses the site the next time and I need to retrieve info from the session store yet again?

Or am I thinking of sessions in the wrong way completely? This is my first time trying to create something with sessions so I have a strong feeling that I'm missing some basic concept.


Solution

  • A cookie is used to identify the session or store the session data depending on the session store used. Two incognito windows in the same browser instance share the same cookies and therefore will share the same session. Try one of of the following: compare sessions in different browser instances (see browser command line help for how to start separate instances), compare sessions between incognito and non-incognito, compares sessions between Edge and Chrome.