-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokengenerator.go
54 lines (42 loc) · 1.16 KB
/
tokengenerator.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
package auth
import (
"errors"
"gopkg.in/dgrijalva/jwt-go.v2"
)
// Errors returned from TokenGenerator
var (
ErrTokenInvalid = errors.New("Token is invalid")
)
// TokenGenerator generates and verifies tokens
type TokenGenerator struct {
method SigningMethod
}
// NewTokenGenerator creates a new token generator
func NewTokenGenerator(method SigningMethod) *TokenGenerator {
return &TokenGenerator{
method: method,
}
}
// Create creates a new token using the correct method
func (t *TokenGenerator) Create() *jwt.Token {
return jwt.New(t.method.Method())
}
// Sign signs the token and returns its string
func (t *TokenGenerator) Sign(token *jwt.Token) (string, error) {
kid := t.method.KID()
token.Header["kid"] = kid
return token.SignedString(t.method.PrivateKey(kid))
}
// Verify verifies and parses a token string
func (t *TokenGenerator) Verify(str string) (*jwt.Token, error) {
token, err := jwt.Parse(str, func(token *jwt.Token) (interface{}, error) {
if token.Header["alg"] != t.method.Method().Alg() {
return nil, ErrTokenInvalid
}
return t.method.PublicKey(token.Header["kid"]), nil
})
if err != nil {
return nil, err
}
return token, nil
}