目录
1、代码实现样例
2、postman调用
1、代码实现样例
package mainimport ("net/http""strings""github.com/dgrijalva/jwt-go""github.com/gin-gonic/gin"
)var (// 密钥,用于验证 JWT 令牌signingKey = []byte("secret")
)// AuthMiddleware 是一个 Gin 中间件函数,用于验证 JWT 令牌
func AuthMiddleware() 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}// 从 Authorization 头部提取令牌parts := strings.Split(authHeader, " ")if len(parts) != 2 || parts[0] != "Bearer" {c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid Authorization header format"})c.Abort()return}tokenString := parts[1]// 解析令牌token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {return signingKey, nil})if err != nil {c.JSON(http.StatusUnauthorized, gin.H{"error": "Failed to parse 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 {c.Set("username", claims["username"])c.Next()} else {c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token claims"})c.Abort()return}}
}func main() {r := gin.Default()// 使用中间件进行认证r.Use(AuthMiddleware())// 受保护的路由,需要认证通过才能访问r.GET("/protected", func(c *gin.Context) {username, _ := c.Get("username")c.JSON(http.StatusOK, gin.H{"message": "Hello, " + username.(string)})})// 启动服务r.Run(":8080")
}
2、postman调用
使用先前生成的token,控制权限,参看我上一篇文章: