-
Notifications
You must be signed in to change notification settings - Fork 15
/
token.go
95 lines (78 loc) · 2.34 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package token
import (
"errors"
"fmt"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)
var (
// ErrMissingHeader means the `Authorization` header was empty.
ErrMissingHeader = errors.New("The length of the `Authorization` header is zero.")
)
// Context is the context of the JSON web token.
type Context struct {
ID uint64
Username string
}
// secretFunc validates the secret format.
func secretFunc(secret string) jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
// Make sure the `alg` is what we except.
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return []byte(secret), nil
}
}
// Parse validates the token with the specified secret,
// and returns the context if the token was valid.
func Parse(tokenString string, secret string) (*Context, error) {
ctx := &Context{}
// Parse the token.
token, err := jwt.Parse(tokenString, secretFunc(secret))
// Parse error.
if err != nil {
return ctx, err
// Read the token if it's valid.
} else if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
ctx.ID = uint64(claims["id"].(float64))
ctx.Username = claims["username"].(string)
return ctx, nil
// Other errors.
} else {
return ctx, err
}
}
// ParseRequest gets the token from the header and
// pass it to the Parse function to parses the token.
func ParseRequest(c *gin.Context) (*Context, error) {
header := c.Request.Header.Get("Authorization")
// Load the jwt secret from config
secret := viper.GetString("jwt_secret")
if len(header) == 0 {
return &Context{}, ErrMissingHeader
}
var t string
// Parse the header to get the token part.
fmt.Sscanf(header, "Bearer %s", &t)
return Parse(t, secret)
}
// Sign signs the context with the specified secret.
func Sign(ctx *gin.Context, c Context, secret string) (tokenString string, err error) {
// Load the jwt secret from the Gin config if the secret isn't specified.
if secret == "" {
secret = viper.GetString("jwt_secret")
}
// The token content.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": c.ID,
"username": c.Username,
"nbf": time.Now().Unix(),
"iat": time.Now().Unix(),
})
// Sign the token with the specified secret.
tokenString, err = token.SignedString([]byte(secret))
return
}