-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
79 lines (65 loc) · 1.8 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package jwt
import (
"context"
"crypto/rsa"
"fmt"
"log"
"github.com/golang-jwt/jwt/v4"
)
// Errors.
var (
ErrInvalidToken error = fmt.Errorf("invalid token")
ErrExpiredOrNotReady error = fmt.Errorf("token is either expired or not ready to use")
)
// JSONWebToken is a concrete struct of json web token.
type JSONWebToken struct {
privateKey *rsa.PrivateKey
publicKey *rsa.PublicKey
}
// NewJSONWebToken is a constructor.
func NewJSONWebToken(privateKey, publicKey []byte) *JSONWebToken {
rsaPrivateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privateKey)
if err != nil {
log.Println(err)
}
rsaPublicKey, err := jwt.ParseRSAPublicKeyFromPEM(publicKey)
if err != nil {
log.Println(err)
}
return &JSONWebToken{rsaPrivateKey, rsaPublicKey}
}
// Sign will generate new jwt token.
func (a *JSONWebToken) Sign(ctx context.Context, claims jwt.Claims) (tokenString string, err error) {
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
return token.SignedString(a.privateKey)
}
// Parse will parse the token string to bearer claims.
func (a *JSONWebToken) Parse(ctx context.Context, tokenString string, claims jwt.Claims) (err error) {
token, err := jwt.ParseWithClaims(tokenString, claims, a.keyFunc)
if err = a.checkError(err); err != nil {
return
}
if !token.Valid {
return ErrInvalidToken
}
return
}
func (a *JSONWebToken) keyFunc(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, ErrInvalidToken
}
return a.publicKey, nil
}
func (a *JSONWebToken) checkError(err error) error {
if err == nil {
return err
}
ve, ok := err.(*jwt.ValidationError)
if !ok {
return ErrInvalidToken
}
if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
return ErrExpiredOrNotReady
}
return ErrInvalidToken
}