| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package middleware
- import (
- "github.com/gin-gonic/gin"
- "github.com/golang-jwt/jwt/v4"
- "net/http"
- "newaterobot-process/utils"
- )
- // JWTAuthMiddleware JWT认证中间件
- func JWTAuthMiddleware() gin.HandlerFunc {
- return func(c *gin.Context) {
- if c.Keys == nil {
- c.Keys = make(map[string]any)
- }
- //判断
- var code int
- var data interface{}
- code = http.StatusOK
- //分别从Header和Query Param当中获取 jwt-token
- token := c.GetHeader("JWT-TOKEN")
- if token == "" {
- token = c.Query("JWT-TOKEN")
- }
- // session未中断
- if _, ok := c.Keys[utils.SessionUserIdKey]; ok {
- c.Next()
- }
- if token == "" {
- code = http.StatusUnauthorized
- data = "无法获取token参数"
- } else {
- claim, err := utils.ParseTokenWithDep(token)
- if err != nil {
- switch err.(*jwt.ValidationError).Errors {
- case jwt.ValidationErrorExpired:
- code = http.StatusUnauthorized
- default:
- code = http.StatusUnauthorized
- }
- }
- if code == http.StatusOK {
- c.Keys[utils.SessionUserIdKey] = claim.ID
- c.Keys[utils.SessionDepIdKey] = claim.Dep
- }
- }
- if code != http.StatusOK {
- c.JSON(http.StatusUnauthorized, gin.H{
- "code": code,
- "msg": "token 验证失败",
- "data": data,
- })
- c.Abort()
- return
- }
- c.Next()
- }
- }
|