jwt.go
951 字节
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
package contextdata
import (
"context"
"github.com/golang-jwt/jwt/v4"
"time"
)
type UserToken struct {
UserId int64
CompanyId int64
EmployeeId int64
}
func (tk UserToken) GenerateToken(secret string, expire int64) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = time.Now().Unix() + expire
claims["iat"] = time.Now().Unix()
claims[CtxKeyJwtUserId] = tk.UserId
claims[CtxKeyJwtCompanyId] = tk.CompanyId
claims[CtxKeyJwtEmployeeId] = tk.EmployeeId
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(secret))
}
func ParseToken(ctx context.Context, secret string, tokenStr string) (context.Context, error) {
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
return ctx, err
}
for k, v := range token.Claims.(jwt.MapClaims) {
ctx = context.WithValue(ctx, k, v)
}
return ctx, nil
}