Implement key rotation with EncodeMulti and DecodeMulti
mainTo rotate keys without invalidating existing cookies, use securecookie.EncodeMulti and securecookie.DecodeMulti. This allows you to maintain a set of valid keys (e.g., a 'current' key and a 'previous' key).
- Encoding: Use
securecookie.EncodeMulti(name, value, currentInstance)to ensure new cookies are always signed/encrypted with the latest key. - Decoding: Use
securecookie.DecodeMulti(name, encodedValue, &target, currentInstance, previousInstance...)to check the incoming cookie against all currently valid keys. - Rotation Strategy: When rotating, move the
currentinstance topreviousand set a new instance ascurrent.
// 1. Setup multiple instances for rotation
var cookies = map[string]*securecookie.SecureCookie{
"previous": securecookie.New(
securecookie.GenerateRandomKey(64),
securecookie.GenerateRandomKey(32),
),
"current": securecookie.New(
securecookie.GenerateRandomKey(64),
securecookie.GenerateRandomKey(32),
),
}
// 2. Encode using the current key
// securecookie.EncodeMulti("cookie-name", value, cookies["current"])
// 3. Decode against all valid keys
// err = securecookie.DecodeMulti("cookie-name", cookie.Value, &value, cookies["current"], cookies["previous"])
// 4. Rotate
func Rotate(newCookie *securecookie.SecureCookie) {
cookies["previous"] = cookies["current"]
cookies["current"] = newCookie
}