-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt_rs256.go
87 lines (71 loc) · 1.94 KB
/
jwt_rs256.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
package auth
import (
"encoding/base64"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
type JwtRS256 struct {
PrivateKey string
PublicKey string
Opt SubOptions
}
func NewJwtRS256(opt JwtOptions) *JwtRS256 {
return &JwtRS256{
PrivateKey: opt.PrivateKey,
PublicKey: opt.PublicKey,
Opt: SubOptions{
Exp: opt.Exp,
IgnoreExp: opt.IgnoreExp,
},
}
}
func (rs256 *JwtRS256) Generate(payload jwt.MapClaims) (string, error) {
payload["iat"] = time.Now().Unix()
payload["exp"] = time.Now().Add(rs256.Opt.Exp).Unix()
claims := jwt.NewWithClaims(jwt.SigningMethodRS256, payload)
decodedPrivateKey, err := base64.StdEncoding.DecodeString(rs256.PrivateKey)
if err != nil {
return "", fmt.Errorf("could not decode key: %w", err)
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(decodedPrivateKey)
if err != nil {
return "", fmt.Errorf("could not parse key: %w", err)
}
token, err := claims.SignedString(key)
if err != nil {
return "", err
}
return token, nil
}
func (rs256 *JwtRS256) Verify(token string) (jwt.MapClaims, error) {
decodedPublicKey, err := base64.StdEncoding.DecodeString(rs256.PublicKey)
if err != nil {
return nil, fmt.Errorf("could not decode: %w", err)
}
key, err := jwt.ParseRSAPublicKeyFromPEM(decodedPublicKey)
if err != nil {
return nil, fmt.Errorf("validate: parse key: %w", err)
}
parsedToken, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected method: %s", t.Header["alg"])
}
return key, nil
})
if err != nil {
return nil, err
}
claims, ok := parsedToken.Claims.(jwt.MapClaims)
if !ok || !parsedToken.Valid {
return nil, fmt.Errorf("validate: invalid token")
}
exp, ok := claims["exp"].(float64)
if !ok {
return nil, fmt.Errorf("invalid token")
}
if !rs256.Opt.IgnoreExp && time.Now().Unix() > int64(exp) {
return nil, fmt.Errorf("token expired")
}
return claims, nil
}