75 lines
1.8 KiB
Go
75 lines
1.8 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"oidc-oauth2-server/models"
|
|
"oidc-oauth2-server/services"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func BearerAuth(keyManager *services.KeyManager, db *gorm.DB) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// 检查 Bearer 前缀
|
|
parts := strings.Split(authHeader, " ")
|
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
tokenString := parts[1]
|
|
|
|
// 解析和验证令牌
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
// 验证签名算法
|
|
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
|
|
return nil, jwt.ErrSignatureInvalid
|
|
}
|
|
return keyManager.GetPrivateKey().Public(), nil
|
|
})
|
|
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if !token.Valid {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// 将令牌中的声明存储在上下文中
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok {
|
|
if sub, ok := claims["sub"].(string); ok {
|
|
if userID, err := strconv.ParseUint(sub, 10, 32); err == nil {
|
|
var user models.User
|
|
if err := db.Where("id = ?", uint(userID)).First(&user).Error; err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Set("user_id", user.ID)
|
|
c.Set("scope", claims["scope"].(string))
|
|
}
|
|
}
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|