mirror of
https://github.com/yv1ing/gin-admin.git
synced 2025-10-24 10:12:05 +08:00
添加jwt鉴权中间件
This commit is contained in:
81
internal/middleware/auth.go
Normal file
81
internal/middleware/auth.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"gin-admin/internal/core/config"
|
||||
"gin-admin/pkg/auth"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
systemmodel "gin-admin/internal/model/system"
|
||||
)
|
||||
|
||||
// @Author: yv1ing
|
||||
// @Author: me@yvling.cn
|
||||
// @Date: 2025/8/28 17:31
|
||||
// @Desc: 鉴权中间件
|
||||
|
||||
func extractBearerToken(c *gin.Context) string {
|
||||
authorization := c.GetHeader("Authorization")
|
||||
if authorization == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authorization, " ", 2)
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || parts[1] == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
return parts[1]
|
||||
}
|
||||
|
||||
func JwtMiddleware(whitelist []string) gin.HandlerFunc {
|
||||
var whitelistRegex []*regexp.Regexp
|
||||
for _, pattern := range whitelist {
|
||||
re, err := regexp.Compile(pattern)
|
||||
if err == nil {
|
||||
whitelistRegex = append(whitelistRegex, re)
|
||||
}
|
||||
}
|
||||
|
||||
return func(c *gin.Context) {
|
||||
path := c.Request.URL.Path
|
||||
for _, re := range whitelistRegex {
|
||||
if re.MatchString(path) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
tokenStr := extractBearerToken(c)
|
||||
if tokenStr == "" {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, systemmodel.Response{
|
||||
Code: http.StatusUnauthorized,
|
||||
Info: "请求头Authorization非法或缺失",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := auth.ParseAccessToken(tokenStr, config.Config.SecretKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, jwt.ErrTokenExpired) {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, systemmodel.Response{
|
||||
Code: http.StatusUnauthorized,
|
||||
Info: "Token已过期",
|
||||
})
|
||||
} else {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, systemmodel.Response{
|
||||
Code: http.StatusUnauthorized,
|
||||
Info: "Token不合法",
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("UID", claims.ID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user