Files
learn-golang/Web开发/02go-gin-middleware/middleware_token.go
liumangmang b010f82221 feat(auth): 添加完整的用户认证API项目
- 实现用户注册、登录、JWT令牌认证功能
- 集成Gin、GORM、Viper、Zap等框架
- 添加密码加密、数据库操作、中间件等完整功能
- 配置多环境支持、日志轮转、CORS处理
- 创建完整的项目结构和配置文件体系
2025-12-30 18:00:42 +08:00

70 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"strings"
"github.com/gin-gonic/gin"
)
// Token 认证中间件
func TokenAuth() gin.HandlerFunc {
return func(c *gin.Context) {
// 从请求头获取 token
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(401, gin.H{"error": "Missing Authorization header"})
c.Abort()
return
}
// 验证 token 格式Bearer xxx
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
c.JSON(401, gin.H{"error": "Invalid Authorization header"})
c.Abort()
return
}
token := parts[1]
// 验证 token 有效性(简化版,实际应使用 JWT
if !isValidToken(token) {
c.JSON(401, gin.H{"error": "Invalid token"})
c.Abort()
return
}
// 提取用户信息(从 token
userID := extractUserID(token)
c.Set("user_id", userID)
c.Next()
}
}
// 验证 token示例
func isValidToken(token string) bool {
return token == "valid_token_123"
}
// 提取用户ID示例
func extractUserID(token string) string {
return "user123"
}
func main() {
r := gin.Default()
// 需要 token 的路由
r.GET("/profile", TokenAuth(), func(c *gin.Context) {
userID := c.GetString("user_id")
c.JSON(200, gin.H{
"user_id": userID,
"profile": "User profile data",
})
})
r.Run(":9999")
}