-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
43 lines (38 loc) · 1013 Bytes
/
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
package util
import (
"github.com/Michael-Johy/go-pkgs-practise/gin/pkg/setting"
"github.com/dgrijalva/jwt-go"
"time"
)
var jwtSecret = []byte(setting.JwtSecret)
type Claims struct {
Username string `json:"username"`
Password string `json:"password"`
jwt.StandardClaims
}
func GenerateToken(username string, password string) (token string, err error) {
nowTime := time.Now()
expiredTime := nowTime.Add(1 * time.Minute)
claims := Claims{
username,
password,
jwt.StandardClaims{
ExpiresAt: expiredTime.Unix(),
Issuer: "",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err = tokenClaims.SignedString(jwtSecret)
return
}
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
}