forked from razonyang/clevergo-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
58 lines (49 loc) · 1.23 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
package core
import (
"errors"
"fmt"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
type JWTManager struct {
secretKey []byte
duration time.Duration
}
func NewJWTManager(cfg JWTConfig) *JWTManager {
return &JWTManager{
secretKey: []byte(cfg.SecretKey),
duration: time.Duration(cfg.Duration) * time.Second,
}
}
func (m *JWTManager) New(userID string) (string, error) {
now := time.Now()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{
IssuedAt: now.Unix(),
NotBefore: now.Unix(),
ExpiresAt: now.Add(m.duration).Unix(),
Subject: userID,
})
return token.SignedString(m.secretKey)
}
func (m *JWTManager) Parse(s string) (*jwt.StandardClaims, error) {
token, err := jwt.ParseWithClaims(s, &jwt.StandardClaims{}, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return m.secretKey, nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, errors.New("invalid token")
}
claims, ok := token.Claims.(*jwt.StandardClaims)
if !ok {
return nil, errors.New("invalid claims")
}
if err = claims.Valid(); err != nil {
return nil, err
}
return claims, nil
}