This repository has been archived by the owner on Jul 26, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
/
jwt.go
83 lines (78 loc) · 2.47 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
package models
import (
"errors"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"time"
)
func jwtGenerateToken(m *AuthorizationModel) (*jwtObj, error) {
m.Password = ""
expireAfterTime := time.Hour * time.Duration(viper.GetInt("app.jwt_expire_hour"))
iss := viper.GetString("app.name")
appSecret := viper.GetString("app.secret")
expireTime := time.Now().Add(expireAfterTime)
stdClaims := jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
IssuedAt: time.Now().Unix(),
Id: fmt.Sprintf("%d", m.Id),
Issuer: iss,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, stdClaims)
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(appSecret))
if err != nil {
logrus.WithError(err).Fatal("config is wrong, can not generate jwt")
}
data := &jwtObj{AuthorizationModel: *m, Token: tokenString, Expire: expireTime, ExpireTs: expireTime.Unix()}
return data, err
}
type jwtObj struct {
AuthorizationModel
Token string `json:"token"`
Expire time.Time `json:"expire"`
ExpireTs int64 `json:"expire_ts"`
}
//JwtParseUser parse a jwt token and return an authorized identity
func JwtParseUser(tokenString string) (*AuthorizationModel, error) {
if tokenString == "" {
return nil, errors.New("token is not found in Authorization Bearer")
}
claims := jwt.StandardClaims{}
_, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
secret := viper.GetString("app.secret")
return []byte(secret), nil
})
if err != nil {
return nil, err
}
if claims.VerifyExpiresAt(time.Now().Unix(), true) == false {
return nil, errors.New("token is expired")
}
appName := viper.GetString("app.name")
if !claims.VerifyIssuer(appName, true) {
return nil, errors.New("token's issuer is wrong,greetings Hacker")
}
key := fmt.Sprintf("login:%s", claims.Id)
jwtObj, err := mem.GetJwtObj(key)
if err != nil {
return nil, err
}
return &jwtObj.AuthorizationModel, err
}
//get an authorized user form memory store
func (s *memoryStore) GetJwtObj(id string) (value *jwtObj, err error) {
vv, err := s.Get(id, false)
if err != nil {
return nil, err
}
value, ok := vv.(*jwtObj)
if ok {
return value, nil
}
return nil, errors.New("mem:has value of this id, but is not type of *jwtObj")
}