user3033143
user3033143

Reputation: 51

Golang Gorilla/session

I'm trying to build a simple web application with a user login.

I found this function in another post here.

func initSession(r *http.Request) *sessions.Session {
    session, _ := store.Get(r, "mBoxStore")
    if session.IsNew {
        session.Options.Domain = "localhost"
        session.Options.MaxAge = 10
        session.Options.HttpOnly = false
        session.Options.Secure = false
        log.Println("Create New Session (cookie)")
    } else {
        log.Println("Use Old Session (old cookie)")
    }
    return session
}

The cookie expires after 10 seconds, but when i reload the page after e.g. 1 Minute it use the old (expired) cookie.

In my browser (Firefox) i see the cookie with the right expire date.

I think it should create a new session with a new cookie or it is wrong ?

any tips ?

Upvotes: 4

Views: 5205

Answers (1)

elithrar
elithrar

Reputation: 24250

The reason you're seeing Use Old Session (old cookie) is because the session options are only being set when the cookie is first created. Each time you access the cookie before it expires (isNew == false) Options are not being set, and the defaults are overriding those you set on creation of the session. The default MaxAge is 86400 * 30 (one month).

You can verify this by:

  1. Clearing all cookies for the site (i.e. localhost)
  2. Bringing up a route in your browser
  3. Checking the expiry date on the freshly created cookie - you'll see it's now + 10 seconds
  4. Wait out that 10 seconds.
  5. Refresh the page - your log should confirm it's a new cookie.
  6. Now refresh the page before the cookie expires (i.e. within 10 seconds)
  7. You'll see the expiry has an expiry of now + 1 month (the default).

This is why I suggest setting your session options once, on application startup. Only deviate if you are setting shorter cookie lifetimes for authentication security purposes, and in those cases use a different session name (i.e. _csrf_token with an expiry of 4 hours).

The code snippet you're using isn't really ideal either as it completely ignores any errors encountered when trying to retrieve a session. You might run into errors if your underlying session store is broken, and/or the user has cookies disabled.

Upvotes: 5

Related Questions