-
Notifications
You must be signed in to change notification settings - Fork 0
/
pkg.go
90 lines (67 loc) · 1.89 KB
/
pkg.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
package securityx
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/go-errors/errors"
"github.com/meiguonet/mgboot-go-common/util/castx"
BuiltinException "github.com/meiguonet/mgboot-go/exception"
"io/ioutil"
"time"
)
func ParseJsonWebToken(token string, pubpem interface{}) (*jwt.Token, error) {
keyBytes := loadJwtPublicKeyPem(pubpem)
if len(keyBytes) < 1 {
return nil, errors.New("fail to load public key from pem file")
}
publicKey, err := jwt.ParseRSAPublicKeyFromPEM(keyBytes)
if err != nil {
return nil, err
}
return jwt.Parse(token, func(tk *jwt.Token) (interface{}, error) {
if _, ok := tk.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", tk.Header["alg"])
}
return publicKey, nil
})
}
func VerifyJsonWebToken(arg0 interface{}, settings *JwtSettings) error {
var token *jwt.Token
if tk, ok := arg0.(*jwt.Token); ok {
token = tk
} else if s1, ok := arg0.(string); ok && s1 != "" {
tk, _ := ParseJsonWebToken(s1, settings)
token = tk
}
if token == nil || !token.Valid {
return BuiltinException.NewAccessTokenInvalidException()
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return BuiltinException.NewAccessTokenInvalidException()
}
iss := settings.Issuer()
if iss != "" && castx.ToString(claims["iss"]) != iss {
return BuiltinException.NewAccessTokenInvalidException()
}
exp := castx.ToInt64(claims["exp"])
if exp > 0 && time.Now().Unix() > exp {
return BuiltinException.NewAccessTokenExpiredException()
}
return nil
}
func loadJwtPublicKeyPem(arg0 interface{}) []byte {
var fpath string
if s1, ok := arg0.(string); ok && s1 != "" {
fpath = s1
} else if s1, ok := arg0.(*JwtSettings); ok && s1 != nil {
fpath = s1.PublicKeyPemFile()
}
if fpath == "" {
return make([]byte, 0)
}
buf, err := ioutil.ReadFile(fpath)
if err != nil {
return make([]byte, 0)
}
return buf
}