-
Notifications
You must be signed in to change notification settings - Fork 6
/
jwt.go
61 lines (53 loc) · 1.28 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
package utils
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"reflect"
"time"
)
var (
secret []byte = []byte("Hello World!This is jwt test demo!")
)
func GenToken(name, pwd string) (string, int) {
claims := &jwt.StandardClaims{
Id: name,
NotBefore: int64(time.Now().Unix()),
ExpiresAt: int64(time.Now().Unix() + 1800000*6),
Issuer: "Bitch",
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(secret)
if err != nil {
return err.Error(), SiginErr
}
return ss, Success
}
func CheckToken(token string) (string, int) {
_, err := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
return secret, nil
})
if err != nil {
return err.Error(), AuthorizeErr
}
return "", Success
}
func ParseToken(tokenSrt string, SecretKey []byte) (claims jwt.Claims, err error) {
var token *jwt.Token
token, err = jwt.Parse(tokenSrt, func(*jwt.Token) (interface{}, error) {
return SecretKey, nil
})
claims = token.Claims
return
}
func GetNameFromClaims(key string, claims jwt.Claims) string {
v := reflect.ValueOf(claims)
if v.Kind() == reflect.Map {
for _, k := range v.MapKeys() {
value := v.MapIndex(k)
if fmt.Sprintf("%s", k.Interface()) == key {
return fmt.Sprintf("%v", value.Interface())
}
}
}
return ""
}