fix
zhangqian
2024-03-29 5124a64edfbcf43c8d4e9d6c396c2ebc3b31c795
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package middleware
 
import (
    "github.com/gin-gonic/gin"
    "outsourcing/conf"
    "outsourcing/pkg/contextx"
    "outsourcing/pkg/ecode"
    "outsourcing/utils/jwt"
    "strings"
)
 
func JWTAuth() gin.HandlerFunc {
    return func(c *gin.Context) {
        ctx := new(contextx.Context).SetCtx(c)
        // 我们这里jwt鉴权取头部信息 Authorization 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
        token := c.Request.Header.Get("Authorization")
        if token == "" {
            ctx.Fail(ecode.JWTEmpty)
            c.Abort()
            return
        }
        slices := strings.Split(token, " ")
        if len(slices) == 2 {
            token = slices[1]
        }
        j := jwt.NewOutsideJWT(conf.WebConf.JWTKey)
        // parseToken 解析token包含的信息
        claims, err := j.ParseToken(token)
        if err != nil {
            if err == jwt.TokenExpired {
                ctx.Fail(ecode.JWTExpire)
                c.Abort()
                return
            }
            ctx.Fail(ecode.JWTParseErr)
            c.Abort()
            return
        }
        if claims.CompanyId == 0 {
            ctx.Fail(ecode.JWTExpire)
            c.Abort()
            return
        }
        c.Set("claims", claims)
        c.Next()
    }
}