-
Notifications
You must be signed in to change notification settings - Fork 2
/
jwt.go
107 lines (90 loc) · 2.21 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
101
102
103
104
105
106
107
package jwt
import (
"fmt"
proxy "github.com/dgrijalva/jwt-go"
"time"
)
type BaseToken struct {
UID int `json:"uid"` // id
OID int `json:"oid"` // organization
Type int32 `json:"type"` // 登录方式
}
type TokenReq struct {
BaseToken
Audience string
Subject string
Expire time.Duration
}
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 TokenReq) (claims *Claims, expire time.Duration, signedToken string, success bool) {
claims = &Claims{
BaseToken: t.BaseToken,
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
}
if t.Expire > 0 {
expire = t.Expire
} else {
expire = h.expire
}
claims.ExpiresAt = time.Now().Add(expire).Unix()
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)
}
if success {
success = claims.VerifyExpiresAt(time.Now().Unix(), true)
}
return
}
// CreateToken create tokenApi
func (h *Handler) CreateToken(claims *Claims) (signedToken string, success bool) {
token := proxy.NewWithClaims(proxy.SigningMethodHS256, claims)
signedToken, err := token.SignedString(h.key)
if err != nil {
return
}
success = true
return
}
// ValidateToken validate tokenApi
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
}