Reputation: 51
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
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:
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