-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.go
50 lines (40 loc) · 1.02 KB
/
token.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
package main
import (
"errors"
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
)
type customClaims struct {
jwt.StandardClaims
SID string
}
func createToken(sid string) (string, error) {
cc := customClaims{
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(5 * time.Minute).Unix(),
},
SID: sid,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, cc)
st, err := token.SignedString(key)
if err != nil {
return "", fmt.Errorf("couldn't sign token in createToken %w", err)
}
return st, nil
}
func parseToken(st string) (string, error) {
token, err := jwt.ParseWithClaims(st, &customClaims{}, func(t *jwt.Token) (interface{}, error) {
if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {
return nil, errors.New("parseWithClaims different algorithms used")
}
return key, nil
})
if err != nil {
return "", fmt.Errorf("couldn't ParseWithClaims in parseToken %w", err)
}
if !token.Valid {
return "", fmt.Errorf("token not valid in parseToken")
}
return token.Claims.(*customClaims).SID, nil
}