From 2e642ff13c59a7e23babe9209c1a114ef0163bad Mon Sep 17 00:00:00 2001 From: aeneasr <3372410+aeneasr@users.noreply.github.com> Date: Mon, 27 Jul 2020 12:34:37 +0200 Subject: [PATCH] feat: implement max-age for session cookie Closes #326 --- .schema/config.schema.json | 3 +-- driver/configuration/provider_viper.go | 10 ++++++++-- session/manager_http.go | 7 ++++++- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/.schema/config.schema.json b/.schema/config.schema.json index 72f70863ccc..5964dc428f4 100644 --- a/.schema/config.schema.json +++ b/.schema/config.schema.json @@ -855,10 +855,9 @@ "properties": { "lifespan": { "title": "Session Lifespan", - "description": "Defines how long a session is active. This value is ignored if the \"remember me\" feature is used.", + "description": "Defines how long a session is active. This value is ignored if the \"remember me\" feature is used. If unset (default), the cookie's `Max-Age` will not be set.", "type": "string", "pattern": "^[0-9]+(ns|us|ms|s|m|h)$", - "default": "1h", "examples": [ "1h", "1m", diff --git a/driver/configuration/provider_viper.go b/driver/configuration/provider_viper.go index a0fd56c299f..175a40713e8 100644 --- a/driver/configuration/provider_viper.go +++ b/driver/configuration/provider_viper.go @@ -379,8 +379,14 @@ func (p *ViperProvider) SelfServiceFlowRecoveryUI() *url.URL { return mustParseURLFromViper(p.l, ViperKeySelfServiceRecoveryUI) } -func (p *ViperProvider) SessionLifespan() time.Duration { - return viperx.GetDuration(p.l, ViperKeySessionLifespan, time.Hour) +// SessionLifespan returns nil when the value is not set. +func (p *ViperProvider) SessionLifespan() *time.Duration { + if viper.Get(ViperKeySessionLifespan) == nil { + return nil + } + + d := viper.GetDuration(ViperKeySessionLifespan) + return &d } func (p *ViperProvider) SelfServiceBrowserWhitelistedReturnToDomains() (us []url.URL) { diff --git a/session/manager_http.go b/session/manager_http.go index e938650df81..cdb85f3bb6d 100644 --- a/session/manager_http.go +++ b/session/manager_http.go @@ -23,7 +23,7 @@ type ( x.CSRFProvider } managerHTTPConfiguration interface { - SessionLifespan() time.Duration + SessionLifespan() *time.Duration SecretsSession() [][]byte SessionSameSiteMode() http.SameSite SessionDomain() string @@ -71,6 +71,11 @@ func (s *ManagerHTTP) SaveToRequest(ctx context.Context, w http.ResponseWriter, if s.c.SessionSameSiteMode() != 0 { cookie.Options.SameSite = s.c.SessionSameSiteMode() } + + if s.c.SessionLifespan() != nil { + cookie.Options.MaxAge = int(s.c.SessionLifespan().Seconds()) + } + cookie.Values["sid"] = session.ID.String() if err := cookie.Save(r, w); err != nil { return errors.WithStack(err)