-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
56 lines (48 loc) · 1.7 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
package jwt
import (
"errors"
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
)
var secret = "asfdeisaufhwe"
// WeChat jwt
type WeChat struct {
}
// Token 生成 Token 传入的 uid, ouid 请加密 iss
func (w *WeChat) Token(openid, appid, nickname string) (tokenString string, err error) {
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"openid": openid,
"appid": appid,
"nickname": nickname,
"nbf": time.Now().Unix(),
"exp": time.Now().Add(36000 * time.Hour).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err = token.SignedString([]byte(secret))
return
}
// Parse ...
func (w *WeChat) Parse(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte(secret), nil
}
// Verify 验证 token 有效性 (加密后的user_id)
func (w *WeChat) Verify(tokenString string) (openid, appid, nickname string, err error) {
token, err := jwt.Parse(tokenString, w.Parse)
if err != nil {
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// unionid, openid, appid, nickname = claims["union_id"].(string), claims["open_id"].(string), claims["app_id"].(string), claims["nick_name"].(string)
return claims["openid"].(string), claims["appid"].(string), claims["nickname"].(string), nil
}
err = errors.New("JWT ERROR")
return
}