mirror of
https://github.com/gofiber/fiber.git
synced 2025-05-31 11:52:41 +00:00
Merge pull request #959 from kiyonlin/improve-csrf
👷 Improve csrf middleware
This commit is contained in:
commit
e619451d9e
@ -149,7 +149,9 @@ func New(config ...Config) fiber.Handler {
|
|||||||
// Return new handler
|
// Return new handler
|
||||||
return func(c *fiber.Ctx) error {
|
return func(c *fiber.Ctx) error {
|
||||||
// Don't execute middleware if Next returns true
|
// Don't execute middleware if Next returns true
|
||||||
if cfg.Next != nil && cfg.Next(c) {
|
if (cfg.Next != nil && cfg.Next(c)) ||
|
||||||
|
// Or non GET/POST method
|
||||||
|
(c.Method() != fiber.MethodGet && c.Method() != fiber.MethodPost) {
|
||||||
return c.Next()
|
return c.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -162,7 +164,7 @@ func New(config ...Config) fiber.Handler {
|
|||||||
token = utils.UUID()
|
token = utils.UUID()
|
||||||
// Add token with timestamp expiration
|
// Add token with timestamp expiration
|
||||||
db.Lock()
|
db.Lock()
|
||||||
db.tokens[token] = int64(time.Now().Unix()) + expiration
|
db.tokens[token] = time.Now().Unix() + expiration
|
||||||
db.Unlock()
|
db.Unlock()
|
||||||
} else {
|
} else {
|
||||||
// Use the server generated token previously to compare
|
// Use the server generated token previously to compare
|
||||||
@ -187,6 +189,13 @@ func New(config ...Config) fiber.Handler {
|
|||||||
if !ok || time.Now().Unix() >= t {
|
if !ok || time.Now().Unix() >= t {
|
||||||
return fiber.ErrForbidden
|
return fiber.ErrForbidden
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Delete token from DB
|
||||||
|
db.Lock()
|
||||||
|
delete(db.tokens, csrf)
|
||||||
|
db.Unlock()
|
||||||
|
|
||||||
|
return c.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create new cookie to send new CSRF token
|
// Create new cookie to send new CSRF token
|
||||||
@ -195,7 +204,7 @@ func New(config ...Config) fiber.Handler {
|
|||||||
Value: token,
|
Value: token,
|
||||||
Domain: cfg.Cookie.Domain,
|
Domain: cfg.Cookie.Domain,
|
||||||
Path: cfg.Cookie.Path,
|
Path: cfg.Cookie.Path,
|
||||||
Expires: time.Now().Add(cfg.CookieExpires),
|
Expires: time.Now().Add(cfg.Expiration),
|
||||||
Secure: cfg.Cookie.Secure,
|
Secure: cfg.Cookie.Secure,
|
||||||
HTTPOnly: cfg.Cookie.HTTPOnly,
|
HTTPOnly: cfg.Cookie.HTTPOnly,
|
||||||
SameSite: cfg.Cookie.SameSite,
|
SameSite: cfg.Cookie.SameSite,
|
||||||
|
Loading…
x
Reference in New Issue
Block a user