-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
executable file
·53 lines (41 loc) · 1.04 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
package util
import (
"time"
"github.com/dgrijalva/jwt-go"
)
var jwtSecret []byte
type Auth struct {
Username string `bson:"username"json:"username"`
Role string `bson:"role"json:"role"`
}
type Claims struct {
Auth Auth
jwt.StandardClaims
}
// GenerateToken generate tokens used for auth
func GenerateToken(auth Auth, jwtExpireTime time.Duration) (string, error) {
nowTime := time.Now()
expireTime := nowTime.Add(jwtExpireTime)
claims := Claims{
auth,
jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "gin-blog",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
// ParseToken parsing token
func ParseToken(token string) (*Claims, error) {
tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if tokenClaims != nil {
if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
return claims, nil
}
}
return nil, err
}