| 1 |
//go:build go1.11 |
| 2 |
// +build go1.11 |
| 3 |
|
| 4 |
package csrf |
| 5 |
|
| 6 |
import ( |
| 7 |
"net/http" |
| 8 |
"time" |
| 9 |
|
| 10 |
"github.com/gorilla/securecookie" |
| 11 |
) |
| 12 |
|
| 13 |
// store represents the session storage used for CSRF tokens. |
| 14 |
type store interface { |
| 15 |
// Get returns the real CSRF token from the store. |
| 16 |
Get(*http.Request) ([]byte, error) |
| 17 |
// Save stores the real CSRF token in the store and writes a |
| 18 |
// cookie to the http.ResponseWriter. |
| 19 |
// For non-cookie stores, the cookie should contain a unique (256 bit) ID |
| 20 |
// or key that references the token in the backend store. |
| 21 |
// csrf.GenerateRandomBytes is a helper function for generating secure IDs. |
| 22 |
Save(token []byte, w http.ResponseWriter) error |
| 23 |
} |
| 24 |
|
| 25 |
// cookieStore is a signed cookie session store for CSRF tokens. |
| 26 |
type cookieStore struct { |
| 27 |
name string |
| 28 |
maxAge int |
| 29 |
secure bool |
| 30 |
httpOnly bool |
| 31 |
path string |
| 32 |
domain string |
| 33 |
sc *securecookie.SecureCookie |
| 34 |
sameSite SameSiteMode |
| 35 |
} |
| 36 |
|
| 37 |
// Get retrieves a CSRF token from the session cookie. It returns an empty token |
| 38 |
// if decoding fails (e.g. HMAC validation fails or the named cookie doesn't exist). |
| 39 |
func (cs *cookieStore) Get(r *http.Request) ([]byte, error) { |
| 40 |
// Retrieve the cookie from the request |
| 41 |
cookie, err := r.Cookie(cs.name) |
| 42 |
if err != nil { |
| 43 |
return nil, err |
| 44 |
} |
| 45 |
|
| 46 |
token := make([]byte, tokenLength) |
| 47 |
// Decode the HMAC authenticated cookie. |
| 48 |
err = cs.sc.Decode(cs.name, cookie.Value, &token) |
| 49 |
if err != nil { |
| 50 |
return nil, err |
| 51 |
} |
| 52 |
|
| 53 |
return token, nil |
| 54 |
} |
| 55 |
|
| 56 |
// Save stores the CSRF token in the session cookie. |
| 57 |
func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error { |
| 58 |
// Generate an encoded cookie value with the CSRF token. |
| 59 |
encoded, err := cs.sc.Encode(cs.name, token) |
| 60 |
if err != nil { |
| 61 |
return err |
| 62 |
} |
| 63 |
|
| 64 |
cookie := &http.Cookie{ |
| 65 |
Name: cs.name, |
| 66 |
Value: encoded, |
| 67 |
MaxAge: cs.maxAge, |
| 68 |
HttpOnly: cs.httpOnly, |
| 69 |
Secure: cs.secure, |
| 70 |
SameSite: http.SameSite(cs.sameSite), |
| 71 |
Path: cs.path, |
| 72 |
Domain: cs.domain, |
| 73 |
} |
| 74 |
|
| 75 |
// Set the Expires field on the cookie based on the MaxAge |
| 76 |
// If MaxAge <= 0, we don't set the Expires attribute, making the cookie |
| 77 |
// session-only. |
| 78 |
if cs.maxAge > 0 { |
| 79 |
cookie.Expires = time.Now().Add( |
| 80 |
time.Duration(cs.maxAge) * time.Second) |
| 81 |
} |
| 82 |
|
| 83 |
// Write the authenticated cookie to the response. |
| 84 |
http.SetCookie(w, cookie) |
| 85 |
|
| 86 |
return nil |
| 87 |
} |