feat(auth): add CSRF protection middleware

Implement Signed Double Submit Cookie pattern to prevent CSRF attacks.
Adds CSRF token generation, validation, and middleware for API endpoints.
Safe methods (GET/HEAD/OPTIONS) automatically receive CSRF cookies, while
unsafe methods require X-CSRF-Token header matching the cookie value with
valid HMAC signature. Includes same-origin exemption for login/callback
endpoints to support browser-based authentication flows.
This commit is contained in:
yusing
2026-03-19 14:55:47 +08:00
parent a541d75bb5
commit 213e4a5cdb
6 changed files with 480 additions and 5 deletions

View File

@@ -56,11 +56,11 @@ func NewHandler(requireAuth bool) *gin.Engine {
if auth.IsEnabled() && requireAuth {
v1Auth := r.Group("/api/v1/auth")
{
v1Auth.HEAD("/check", authApi.Check)
v1Auth.POST("/login", authApi.Login)
v1Auth.HEAD("/check", CSRFMiddleware(), authApi.Check)
v1Auth.POST("/login", CSRFMiddleware(), authApi.Login)
v1Auth.GET("/callback", authApi.Callback)
v1Auth.POST("/callback", authApi.Callback)
v1Auth.POST("/logout", authApi.Logout)
v1Auth.POST("/callback", CSRFMiddleware(), authApi.Callback)
v1Auth.POST("/logout", CSRFMiddleware(), authApi.Logout)
v1Auth.GET("/logout", authApi.Logout)
}
}
@@ -68,6 +68,7 @@ func NewHandler(requireAuth bool) *gin.Engine {
v1 := r.Group("/api/v1")
if auth.IsEnabled() && requireAuth {
v1.Use(AuthMiddleware())
v1.Use(CSRFMiddleware())
}
if common.APISkipOriginCheck {
v1.Use(SkipOriginCheckMiddleware())