-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
59 lines (48 loc) · 1.57 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
package jwt
import (
"fmt"
jwtlib "github.com/dgrijalva/jwt-go"
)
// TokenEncodeString is the byte string used for encoding/decoding JWT tokens.
// It's recommended to change this value for every use of the package
var TokenEncodeString = []byte("dfgr45uty53jyjerghejhgjeaNRghehy5")
// Issuer is the value used as a JWT Claim issuer.
var Issuer = "Distributed, Blockchain and Business Solutions LLC"
// Claims contains the JWT StandardClaims and a data map for custom data
type Claims struct {
Data map[string]interface{}
jwtlib.StandardClaims
}
// CreateToken will create new JWT token with the provided data
func CreateToken(data map[string]interface{}, expires int64) (string, error) {
claims := &Claims{
Data: make(map[string]interface{}),
StandardClaims: jwtlib.StandardClaims{
ExpiresAt: expires,
Issuer: Issuer,
},
}
for k, v := range data {
claims.Data[k] = v
}
token := jwtlib.NewWithClaims(jwtlib.SigningMethodHS256, claims)
token.Claims = claims
return token.SignedString(TokenEncodeString)
}
// ParseToken parses a JWT token and returns the custom data of the token
func ParseToken(t string) (map[string]interface{}, error) {
token, err := jwtlib.ParseWithClaims(t, &Claims{}, func(token *jwtlib.Token) (interface{}, error) {
if _, ok := token.Method.(*jwtlib.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("invalid signing method %v", token.Method)
}
return TokenEncodeString, nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, fmt.Errorf("invalid token")
}
claims := token.Claims.(*Claims)
return claims.Data, nil
}