-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
60 lines (55 loc) · 1.24 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
package main
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"github.com/golang-jwt/jwt"
"github.com/klovercloud-ci/config"
"log"
"time"
)
var RsaKeys *Jwt = nil
type Jwt struct {
PrivateKey *rsa.PrivateKey
PublicKey *rsa.PublicKey
}
func (j Jwt) GetRsaKeys() *Jwt {
if RsaKeys == nil {
RsaKeys = &Jwt{
PrivateKey: j.GetPrivateKey(),
PublicKey: j.GetPublicKey(),
}
}
return RsaKeys
}
func (j Jwt) GenerateToken(duration int64, data interface{}) (string, error) {
token := jwt.New(jwt.SigningMethodRS512)
token.Claims = jwt.MapClaims{
"exp": time.Now().UTC().Add(time.Duration(duration) * time.Hour).Unix(),
"iat": time.Now().UTC().Unix(),
"data": data,
}
tokenString, err := token.SignedString(j.GetRsaKeys().PrivateKey)
if err != nil {
return "", err
}
return tokenString, nil
}
func (Jwt) GetPrivateKey() *rsa.PrivateKey {
block, _ := pem.Decode([]byte(config.PrivateKey))
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
log.Print(err.Error())
panic(err)
}
return key
}
func (Jwt) GetPublicKey() *rsa.PublicKey {
block, _ := pem.Decode([]byte(config.Publickey))
pkey, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
log.Print(err.Error())
panic(err)
}
return pkey
}