-
Notifications
You must be signed in to change notification settings - Fork 155
/
jwt.go
41 lines (36 loc) · 881 Bytes
/
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
package handler
import (
"fmt"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
)
var (
tokenKey = []byte("XXXXXXXXXXXXXXXX")
)
func makeToken(sub string) (token string) {
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{
ExpiresAt: time.Now().Add(7 * 24 * time.Hour).Unix(),
Subject: sub,
})
token, _ = t.SignedString(tokenKey)
return
}
func parseToken(token string) (sub string) {
token = strings.TrimPrefix(token, "Bearer ")
if token == "" {
return
}
t, _ := jwt.ParseWithClaims(token, &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 tokenKey, nil
})
if t != nil {
if claims, ok := t.Claims.(*jwt.StandardClaims); ok && t.Valid {
return claims.Subject
}
}
return
}