2fb9c3ccfd
移除认证中间件中 access_token 查询参数的回退逻辑,防止令牌通过 URL 暴露 - 仅支持 Authorization: Bearer 请求头认证 - 防止令牌被反向代理日志、浏览器历史、监控系统等捕获 - 前端已使用安全的头部认证方式
44 lines
992 B
Go
44 lines
992 B
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/1024XEngineer/xinfra/server/internal/auth"
|
|
"github.com/1024XEngineer/xinfra/server/internal/config"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const ClaimsKey = "claims"
|
|
|
|
func AuthMiddleware(cfg config.Config) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
value := c.GetHeader("Authorization")
|
|
tokenValue := ""
|
|
if strings.HasPrefix(value, "Bearer ") {
|
|
tokenValue = strings.TrimPrefix(value, "Bearer ")
|
|
}
|
|
if tokenValue == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing bearer token"})
|
|
return
|
|
}
|
|
claims, err := auth.Parse(cfg.JWTSecret, tokenValue)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
return
|
|
}
|
|
c.Set(ClaimsKey, claims)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func CurrentClaims(c *gin.Context) (*auth.Claims, bool) {
|
|
value, ok := c.Get(ClaimsKey)
|
|
if !ok {
|
|
return nil, false
|
|
}
|
|
claims, ok := value.(*auth.Claims)
|
|
return claims, ok
|
|
}
|