-
Notifications
You must be signed in to change notification settings - Fork 16
/
jwt.go
58 lines (44 loc) · 1.29 KB
/
jwt.go
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
48
49
50
51
52
53
54
55
56
57
58
package jwt
import (
"github.com/iimeta/iim-client/internal/errors"
"time"
"github.com/golang-jwt/jwt/v4"
)
type Options jwt.RegisteredClaims
type AuthClaims struct {
Guard string `json:"guard"` // 授权守卫
jwt.RegisteredClaims
}
func NewNumericDate(t time.Time) *jwt.NumericDate {
return jwt.NewNumericDate(t)
}
// GenerateToken 生成 JWT 令牌
func GenerateToken(guard string, secret string, ops *Options) string {
claims := AuthClaims{
Guard: guard,
RegisteredClaims: jwt.RegisteredClaims{
Audience: ops.Audience,
ExpiresAt: ops.ExpiresAt,
ID: ops.ID,
IssuedAt: ops.IssuedAt,
Issuer: ops.Issuer,
NotBefore: ops.NotBefore,
Subject: ops.Subject,
},
}
tokenString, _ := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secret))
return tokenString
}
// ParseToken 解析 JWT Token
func ParseToken(token string, secret string) (*AuthClaims, error) {
data, err := jwt.ParseWithClaims(token, &AuthClaims{}, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.Newf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
})
if claims, ok := data.Claims.(*AuthClaims); ok && data.Valid {
return claims, nil
}
return nil, err
}