加密 Cookie
Encrypt Cookie 是一个用于 Fiber 的中间件,通过加密保护你的 cookie 值。
注意
此中间件加密的是 cookie 值,而不是 cookie 名称。
签名
// Intitializes the middleware
func New(config ...Config) fiber.Handler
// Returns a random 32 character long string
func GenerateKey() string
示例
要使用 Encrypt Cookie 中间件,首先需要导入作为 Fiber Web 框架一部分的中间件包
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/encryptcookie"
)
导入中间件包后,你就可以在你的 Fiber app 中使用它了
// Provide a minimal configuration
app.Use(encryptcookie.New(encryptcookie.Config{
Key: "secret-thirty-2-character-string",
}))
// Retrieve the encrypted cookie value
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("value=" + c.Cookies("test"))
})
// Create an encrypted cookie
app.Post("/", func(c *fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "test",
Value: "SomeThing",
})
return nil
})
注意
Key
必须是一个 32 字符长的字符串。它用于加密值,所以请确保它是随机的并且保密。你可以运行 openssl rand -base64 32
或调用 encryptcookie.GenerateKey()
为你生成一个随机密钥。请注意不要将 Key
设置为 encryptcookie.GenerateKey()
,因为这会在每次运行时创建一个新的密钥。
配置
属性 | 类型 | 描述 | 默认值 |
---|---|---|---|
下一页 | func(*fiber.Ctx) bool | 一个函数,当返回 true 时跳过此中间件。 | nil |
排除 | []string | 不应加密的 cookie 键数组。 | [] |
Key | string | 一个 base64 编码的唯一密钥,用于编码和解码 cookie。必需。密钥长度应为 32 个字符。 | (无默认值,必需字段) |
加密器 | func(decryptedString, key string) (string, error) | 一个自定义函数,用于加密 cookie。 | EncryptCookie |
解密器 | func(encryptedString, key string) (string, error) | 一个自定义函数,用于解密 cookie。 | DecryptCookie |
默认配置
var ConfigDefault = Config{
Next: nil,
Except: []string{},
Key: "",
Encryptor: EncryptCookie,
Decryptor: DecryptCookie,
}
与其他读取或修改 Cookie 的中间件一起使用
将 `encryptcookie` 中间件放在任何其他读取或修改 cookie 的中间件之前。例如,如果你正在使用 `CSRF` 中间件,请确保 `encryptcookie` 中间件放在它之前。否则,可能会阻止 `CSRF` 中间件读取加密后的 cookie。
你也可以选择排除某些 cookie 不进行加密。例如,如果你正在将 `CSRF` 中间件与像 Angular 这样的前端框架一起使用,并且该框架从 cookie 中读取 token,则应将该 cookie 排除在加密之外。这可以通过将 cookie 名称添加到配置中的 `Except` 数组来实现
app.Use(encryptcookie.New(encryptcookie.Config{
Key: "secret-thirty-2-character-string",
Except: []string{csrf.ConfigDefault.CookieName}, // exclude CSRF cookie
}))
app.Use(csrf.New(csrf.Config{
KeyLookup: "header:" + csrf.HeaderName,
CookieSameSite: "Lax",
CookieSecure: true,
CookieHTTPOnly: false,
}))