1 Star 2 Fork 0

阿债/fiber-u8l

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
csrf.go 2.28 KB
一键复制 编辑 原始数据 按行查看 历史
阿债 提交于 2021-03-15 10:13 . fiber更新到2.6.0
package csrf
import (
"time"
"gitee.com/azhai/fiber-u8l"
)
// New creates a new middleware handler
func New(config ...Config) fiber.Handler {
// Set default config
cfg := configDefault(config...)
// Create manager to simplify storage operations ( see manager.go )
manager := newManager(cfg.Storage)
dummyValue := []byte{'+'}
// Return new handler
return func(c *fiber.Ctx) (err error) {
// Don't execute middleware if Next returns true
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
var token string
// Action depends on the HTTP method
switch c.Method() {
case fiber.MethodGet, fiber.MethodHead, fiber.MethodOptions, fiber.MethodTrace:
// Declare empty token and try to get existing CSRF from cookie
token = c.Cookies(cfg.CookieName)
default:
// Assume that anything not defined as 'safe' by RFC7231 needs protection
// Extract token from client request i.e. header, query, param, form or cookie
token, err = cfg.extractor(c)
if err != nil {
return cfg.ErrorHandler(c, err)
}
// if token does not exist in Storage
if manager.getRaw(token) == nil {
// Expire cookie
c.Cookie(&fiber.Cookie{
Name: cfg.CookieName,
Domain: cfg.CookieDomain,
Path: cfg.CookiePath,
Expires: time.Now().Add(-1 * time.Minute),
Secure: cfg.CookieSecure,
HTTPOnly: cfg.CookieHTTPOnly,
SameSite: cfg.CookieSameSite,
})
return cfg.ErrorHandler(c, err)
}
}
// Generate CSRF token if not exist
if token == "" {
// And generate a new token
token = cfg.KeyGenerator()
}
// Add/update token to Storage
manager.setRaw(token, dummyValue, cfg.Expiration)
// Create cookie to pass token to client
cookie := &fiber.Cookie{
Name: cfg.CookieName,
Value: token,
Domain: cfg.CookieDomain,
Path: cfg.CookiePath,
Expires: time.Now().Add(cfg.Expiration),
Secure: cfg.CookieSecure,
HTTPOnly: cfg.CookieHTTPOnly,
SameSite: cfg.CookieSameSite,
}
// Set cookie to response
c.Cookie(cookie)
// Protect clients from caching the response by telling the browser
// a new header value is generated
c.Vary(fiber.HeaderCookie)
// Store token in context if set
if cfg.ContextKey != "" {
c.Locals(cfg.ContextKey, token)
}
// Continue stack
return c.Next()
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/azhai/fiber-u8l.git
git@gitee.com:azhai/fiber-u8l.git
azhai
fiber-u8l
fiber-u8l
v1.27.1

搜索帮助