The csrf package uses a store interface to manage the lifecycle of CSRF tokens. If you need to store tokens in a backend database or a distributed cache instead of a cookie, you must implement this interface.
To implement a custom store, provide the following two methods:
Get(*http.Request) ([]byte, error): Retrieves the actual CSRF token from the session storage. If using a non-cookie store, the request's cookie should contain a unique ID (e.g., a 256-bit key) that you use to look up the token in your backend.Save(token []byte, w http.ResponseWriter) error: Persists the token. For non-cookie stores, this method should write a cookie to the http.ResponseWriter containing the unique ID that references the token in your backend.
type MyCustomStore struct {
// your backend client/db
}
func (m *MyCustomStore) Get(r *http.Request) ([]byte, error) {
// 1. Get the ID from the request cookie
// 2. Look up the token in your backend using that ID
// 3. Return the token
return token, nil
}
func (m *MyCustomStore) Save(token []byte, w http.ResponseWriter) error {
// 1. Generate a unique ID (e.g., using csrf.GenerateRandomBytes)
// 2. Store the token in your backend mapped to that ID
// 3. Write a cookie to 'w' containing the ID
return nil
}