-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
63 lines (53 loc) · 1.2 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
package main
import (
"errors"
"time"
"github.com/golang-jwt/jwt"
)
type CustomClaims struct {
UserID int `json:"userID,omitempty"`
jwt.StandardClaims
}
func NewCustomClaims(userID int) CustomClaims {
token := CustomClaims{
UserID: userID,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour).Unix(),
Issuer: "ipaas-backend",
},
}
return token
}
func NewSignedToken(claim CustomClaims) (string, error) {
//unsigned token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
//sign the token
return token.SignedString(JwtSecret)
}
func ParseToken(t string) (CustomClaims, error) {
token, err := jwt.ParseWithClaims(
t,
&CustomClaims{},
func(token *jwt.Token) (interface{}, error) {
return JwtSecret, nil
},
)
if err != nil {
return CustomClaims{}, err
}
claims, ok := token.Claims.(*CustomClaims)
if !ok {
return CustomClaims{}, errors.New("can't parse claims")
}
if claims.ExpiresAt < time.Now().UTC().Unix() {
return CustomClaims{}, errors.New("jwt is expired")
}
return *claims, nil
}
func IsJWTexpired(t string) bool {
claims, err := ParseToken(t)
if err != nil {
return true
}
return claims.ExpiresAt < time.Now().UTC().Unix()
}