File tree Expand file tree Collapse file tree 2 files changed +28
-1
lines changed Expand file tree Collapse file tree 2 files changed +28
-1
lines changed Original file line number Diff line number Diff line change 88type Option func (* csrf )
99
1010// MaxAge sets the maximum age (in seconds) of a CSRF token's underlying cookie.
11- // Defaults to 12 hours.
11+ // Defaults to 12 hours. Call csrf.MaxAge(0) to explicitly set session-only
12+ // cookies.
1213func MaxAge (age int ) Option {
1314 return func (cs * csrf ) {
1415 cs .opts .MaxAge = age
@@ -131,6 +132,9 @@ func parseOptions(h http.Handler, opts ...Option) *csrf {
131132 cs .opts .Secure = true
132133 cs .opts .HttpOnly = true
133134
135+ // Default; only override this if the package user explicitly calls MaxAge(0)
136+ cs .opts .MaxAge = defaultAge
137+
134138 // Range over each options function and apply it
135139 // to our csrf type to configure it. Options functions are
136140 // applied in order, with any conflicting options overriding
Original file line number Diff line number Diff line change @@ -71,3 +71,26 @@ func TestOptions(t *testing.T) {
7171 cs .opts .CookieName , name )
7272 }
7373}
74+
75+ func TestMaxAge (t * testing.T ) {
76+ t .Run ("Ensure the default MaxAge is applied" , func (t * testing.T ) {
77+ handler := Protect (testKey )(nil )
78+ csrf := handler .(* csrf )
79+ cs := csrf .st .(* cookieStore )
80+
81+ if cs .maxAge != defaultAge {
82+ t .Fatalf ("default maxAge not applied: got %d (want %d)" , cs .maxAge , defaultAge )
83+ }
84+ })
85+
86+ t .Run ("Support an explicit MaxAge of 0 (session-only)" , func (t * testing.T ) {
87+ handler := Protect (testKey , MaxAge (0 ))(nil )
88+ csrf := handler .(* csrf )
89+ cs := csrf .st .(* cookieStore )
90+
91+ if cs .maxAge != 0 {
92+ t .Fatalf ("zero (0) maxAge not applied: got %d (want %d)" , cs .maxAge , 0 )
93+ }
94+ })
95+
96+ }
You can’t perform that action at this time.
0 commit comments