22 lines
568 B
Go
22 lines
568 B
Go
package middleware
|
|
|
|
import (
|
|
"crypto/subtle"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// RequireAPIKey 校验 Authorization: Bearer <api_key>(常数时间比较),不匹配返回 401。
|
|
func RequireAPIKey(key string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
token := strings.TrimSpace(strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer "))
|
|
if key == "" || subtle.ConstantTimeCompare([]byte(token), []byte(key)) != 1 {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "UNAUTHORIZED"})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|