/
jwt.go
61 lines (50 loc) · 1.32 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
package jwt
import (
"errors"
"time"
jwtgo "github.com/dgrijalva/jwt-go"
)
var SigningKey = []byte("todo: randomize this key")
type CustomClaims struct {
Id string `json:"id"`
Role string `json:"role"`
jwtgo.StandardClaims
}
// Create the Claims
func CreateJwtWithIdRole(id string, role string, secondsToExpiration int64) (string, error) {
now := time.Now()
claims := CustomClaims{
id,
role,
jwtgo.StandardClaims{
Issuer: "apiservice",
Audience: "apiservice",
IssuedAt: now.Unix(),
ExpiresAt: now.Add(time.Second * time.Duration(secondsToExpiration)).Unix(),
},
}
token := jwtgo.NewWithClaims(jwtgo.SigningMethodHS256, claims)
ss, err := token.SignedString(SigningKey)
return ss, err
}
func keyLookupFunction(token *jwtgo.Token) (interface{}, error) {
// Always return the same SigningKey
return SigningKey, nil
}
func ParseJwt(tokenStr string) (*jwtgo.Token, *CustomClaims, error) {
token, err := jwtgo.ParseWithClaims(tokenStr, &CustomClaims{}, keyLookupFunction)
if err != nil {
return nil, nil, err
}
if token == nil {
return nil, nil, errors.New("Unable to parse token")
}
if token.Claims == nil {
return nil, nil, errors.New("Unable to parse token claims")
}
claims, ok := token.Claims.(*CustomClaims)
if !ok {
panic("Type Assertion failed")
}
return token, claims, err
}