更新依赖项,添加单元测试,优化用户信息和令牌管理功能,增强中间件以支持 JWT 验证,新增访问令牌模型并更新数据库迁移。

This commit is contained in:
2025-04-17 02:04:52 +08:00
parent 83c82f7135
commit d06e45e5d4
10 changed files with 482 additions and 14 deletions

View File

@@ -2,13 +2,18 @@ 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(jwtSecret []byte) gin.HandlerFunc {
func BearerAuth(keyManager *services.KeyManager, db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
@@ -30,10 +35,10 @@ func BearerAuth(jwtSecret []byte) gin.HandlerFunc {
// 解析和验证令牌
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// 验证签名算法
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, jwt.ErrSignatureInvalid
}
return jwtSecret, nil
return keyManager.GetPrivateKey().Public(), nil
})
if err != nil {
@@ -50,8 +55,18 @@ func BearerAuth(jwtSecret []byte) gin.HandlerFunc {
// 将令牌中的声明存储在上下文中
if claims, ok := token.Claims.(jwt.MapClaims); ok {
c.Set("user_id", uint(claims["sub"].(float64)))
c.Set("scope", claims["scope"].(string))
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()