-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
100 lines (78 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
package services
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"time"
"ldt/go-redis/config"
"github.com/golang-jwt/jwt"
)
var (
JwtObj *jwtProvider
ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key")
ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key")
ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key")
)
type jwtProvider struct {
config config.Config
signKey *rsa.PrivateKey
verifyKey *rsa.PublicKey
}
type UserClaimData struct {
UID string `json:"uid"`
LoginTime time.Time `json:"loginTime"`
}
type UserClaim struct {
*jwt.StandardClaims
User UserClaimData `json:"user"`
}
func NewJWT(cfg config.Config) error {
JwtObj = &jwtProvider{config: cfg}
blockPriv, _ := pem.Decode(cfg.PrivBuf)
privKey, err := x509.ParsePKCS1PrivateKey(blockPriv.Bytes)
if err != nil {
return err
}
JwtObj.signKey = privKey
// blockPub, _ := pem.Decode(cfg.PubBuf)
// pubInterface, err := x509.ParsePKIXPublicKey(blockPub.Bytes)
// if err != nil {
// return err
// }
// JwtObj.verifyKey = pubInterface.(*rsa.PublicKey)
JwtObj.verifyKey = &privKey.PublicKey
return nil
}
func (j *jwtProvider) CreateToken(uid string) (string, error) {
t := jwt.New(jwt.SigningMethodRS256)
t.Claims = &UserClaim{
&jwt.StandardClaims{
ExpiresAt: time.Now().Add(j.config.AccessTokenExpiresIn * time.Minute).Unix(),
},
UserClaimData{UID: uid, LoginTime: time.Now()},
}
return t.SignedString(j.signKey)
}
func (j *jwtProvider) CreateRefreshToken(uid string) (string, error) {
t := jwt.New(jwt.SigningMethodRS256)
t.Claims = &UserClaim{
&jwt.StandardClaims{
ExpiresAt: time.Now().Add(j.config.RefreshTokenExpiresIn * time.Minute).Unix(),
},
UserClaimData{UID: uid, LoginTime: time.Now()},
}
return t.SignedString(j.signKey)
}
func (j *jwtProvider) ValidateToken(token string) (interface{}, error) {
tokenParse, err := jwt.ParseWithClaims(token, &UserClaim{}, func(t *jwt.Token) (interface{}, error) {
return j.verifyKey, nil
})
if err != nil {
return nil, err
}
if tokenParse == nil {
return nil, errors.New("cant parse token")
}
return tokenParse.Claims.(*UserClaim), nil
}