-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
100 lines (83 loc) · 2.1 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package jwt
import (
"fmt"
proxy "github.com/dgrijalva/jwt-go"
"time"
)
type BaseToken struct {
UID string `json:"uid"` // id
LoginType int32 `json:"login_type"` // 登录方式
}
type Token struct {
BaseToken
Audience string `json:"aud,omitempty"`
Subject string `json:"sub,omitempty"`
}
type Claims struct {
BaseToken
proxy.StandardClaims
}
type Handler struct {
key []byte // key
expire time.Duration // 有效时间
issuer string
}
func New(key []byte, issuer string, expire time.Duration) Handler {
return Handler{key: key, issuer: issuer, expire: expire}
}
func (h *Handler) GenToken(t Token) (claims *Claims, signedToken string, success bool) {
claims = &Claims{
BaseToken: BaseToken{
UID: t.BaseToken.UID,
LoginType: t.BaseToken.LoginType,
},
StandardClaims: proxy.StandardClaims{
Issuer: h.issuer,
},
}
if len(t.Audience) > 0 {
claims.StandardClaims.Audience = t.Audience
}
if len(t.Subject) > 0 {
claims.StandardClaims.Subject = t.Subject
}
signedToken, success = h.CreateToken(claims)
return
}
func (h *Handler) VerifyToken(signedToken string) (claims *Claims, success bool) {
claims, success = h.ValidateToken(signedToken)
if success {
success = claims.VerifyIssuer(h.issuer, false)
}
return
}
// CreateToken create token
func (h *Handler) CreateToken(claims *Claims) (signedToken string, success bool) {
claims.ExpiresAt = time.Now().Add(h.expire).Unix()
token := proxy.NewWithClaims(proxy.SigningMethodHS256, claims)
signedToken, err := token.SignedString(h.key)
if err != nil {
return
}
success = true
return
}
// ValidateToken validate token
func (h *Handler) ValidateToken(signedToken string) (claims *Claims, success bool) {
token, err := proxy.ParseWithClaims(signedToken, &Claims{},
func(token *proxy.Token) (interface{}, error) {
if _, ok := token.Method.(*proxy.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected login method %v", token.Header["alg"])
}
return h.key, nil
})
if err != nil {
return
}
claims, ok := token.Claims.(*Claims)
if ok && token.Valid {
success = true
return
}
return
}