-
Notifications
You must be signed in to change notification settings - Fork 19
/
kid_keys.go
234 lines (201 loc) · 6.2 KB
/
kid_keys.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package jwt
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)
var (
// ErrEmptyKid fires when the header is missing a "kid" field.
ErrEmptyKid = errors.New("jwt: kid is empty")
// ErrUnknownKid fires when the header has a "kid" field
// but does not match with any of the registered ones.
ErrUnknownKid = errors.New("jwt: unknown kid")
)
type (
// HeaderWithKid represents a simple header part which
// holds the "kid" and "alg" fields.
HeaderWithKid struct {
Kid string `json:"kid"`
Alg string `json:"alg"`
}
// Key holds the Go parsed key pairs.
// This package has all the helpers you need to parse
// a file or a string to go crypto keys,
// e.g. `ParsePublicKeyRSA` and `ParsePrivateKeyRSA` package-level functions.
Key struct {
ID string
Alg Alg
Public PublicKey
Private PrivateKey
MaxAge time.Duration // optional.
Encrypt InjectFunc // optional.
Decrypt InjectFunc // optional.
}
// Keys is a map which holds the key id and a key pair.
// User should initialize the keys once, not safe for concurrent writes.
// See its `SignToken`, `VerifyToken` and `ValidateHeader` methods.
// Usage:
// var keys jwt.Keys
// keys.Register("api", jwt.RS256, apiPubKey, apiPrivKey)
// keys.Register("cognito", jwt.RS256, cognitoPubKey, nil)
// ...
// token, err := keys.SignToken("api", myClaims{...}, jwt.MaxAge(15*time.Minute))
// ...
// var c myClaims
// err := keys.VerifyToken("api", token, &myClaims)
// }
Keys map[string]*Key
// KeysConfiguration for multiple keys sign and validate.
// Look the MustLoad/Load method.
//
// Example at: _examples/multiple-kids.
KeysConfiguration []struct {
ID string `json:"id" yaml:"ID" toml:"ID" ini:"id"`
// Alg declares the algorithm name.
// Available values:
// * HS256
// * HS384
// * HS512
// * RS256
// * RS384
// * RS512
// * PS256
// * PS384
// * PS512
// * ES256
// * ES384
// * ES512
// * EdDSA
Alg string `json:"alg" yaml:"Alg" toml:"Alg" ini:"alg"`
Private string `json:"private" yaml:"Private" toml:"Private" ini:"private"`
Public string `json:"public" yaml:"Public" toml:"Public" ini:"public"`
// MaxAge sets the token expiration. It is optional.
// If greater than zero then the MaxAge token validation
// will be appended to the "VerifyToken" and the token is invalid
// after expiration of its sign time.
MaxAge time.Duration `json:"max_age" yaml:"MaxAge" toml:"MaxAge" ini:"max_age"`
// EncryptionKey enables encryption on the generated token. It is optional.
// Encryption using the Galois Counter mode of operation with
// AES cipher symmetric-key cryptographic.
//
// The value should be the AES key,
// either 16, 24, or 32 bytes to select
// AES-128, AES-192, or AES-256.
EncryptionKey string `json:"encryption_key" yaml:"EncryptionKey" toml:"EncryptionKey" ini:"encryption_key"`
}
)
// MustLoad same as Load but it panics if errored.
func (c KeysConfiguration) MustLoad() Keys {
keys, err := c.Load()
if err != nil {
panic(err)
}
return keys
}
// Load returns the keys parsed through the json, yaml, toml or ini configuration.
func (c KeysConfiguration) Load() (Keys, error) {
parsedKeys := make(Keys, len(c))
for _, entry := range c {
alg := RS256
for _, algo := range allAlgs {
if strings.EqualFold(algo.Name(), entry.Alg) {
alg = algo
break
}
}
p := &Key{
ID: entry.ID,
Alg: alg,
MaxAge: entry.MaxAge,
}
if public, err := strconv.Unquote(entry.Public); err == nil {
entry.Public = public
}
if private, err := strconv.Unquote(entry.Private); err == nil {
entry.Private = private
}
if parser, ok := alg.(AlgParser); ok {
var err error
p.Private, p.Public, err = parser.Parse([]byte(entry.Private), []byte(entry.Public))
if err != nil {
return nil, fmt.Errorf("jwt: load keys: parse: %w", err)
}
} else {
p.Private = entry.Private
p.Public = entry.Public
}
if entry.EncryptionKey != "" {
encrypt, decrypt, err := GCM([]byte(entry.EncryptionKey), nil)
if err != nil {
return nil, fmt.Errorf("jwt: load keys: build encryption: %w", err)
}
p.Encrypt = encrypt
p.Decrypt = decrypt
}
parsedKeys[entry.ID] = p
}
return parsedKeys, nil
}
// Get returns the key based on its id.
func (keys Keys) Get(kid string) (*Key, bool) {
k, ok := keys[kid]
return k, ok
}
// Register registers a keypair to a unique identifier per key.
func (keys Keys) Register(alg Alg, kid string, pubKey PublicKey, privKey PrivateKey) {
keys[kid] = &Key{
ID: kid,
Alg: alg,
Public: pubKey,
Private: privKey,
}
}
// ValidateHeader validates the given json header value (base64 decoded) based on the "keys".
// Keys structure completes the `HeaderValidator` interface.
func (keys Keys) ValidateHeader(alg string, headerDecoded []byte) (Alg, PublicKey, InjectFunc, error) {
var h HeaderWithKid
err := Unmarshal(headerDecoded, &h)
if err != nil {
return nil, nil, nil, err
}
if h.Kid == "" {
return nil, nil, nil, ErrEmptyKid
}
key, ok := keys.Get(h.Kid)
if !ok {
return nil, nil, nil, ErrUnknownKid
}
if h.Alg != key.Alg.Name() {
return nil, nil, nil, ErrTokenAlg
}
// If for some reason a specific alg was given by the caller then check that as well.
if alg != "" && alg != h.Alg {
return nil, nil, nil, ErrTokenAlg
}
return key.Alg, key.Public, key.Decrypt, nil
}
// SignToken signs the "claims" using the given "alg" based a specific key.
func (keys Keys) SignToken(kid string, claims interface{}, opts ...SignOption) ([]byte, error) {
k, ok := keys.Get(kid)
if !ok {
return nil, ErrUnknownKid
}
if k.MaxAge > 0 {
opts = append([]SignOption{MaxAge(k.MaxAge)}, opts...)
}
return SignEncryptedWithHeader(k.Alg, k.Private, k.Encrypt, claims, HeaderWithKid{
Kid: kid,
Alg: k.Alg.Name(),
}, opts...)
}
// VerifyToken verifies the "token" using the given "alg" based on the registered public key(s)
// and sets the custom claims to the destination "claimsPtr".
func (keys Keys) VerifyToken(token []byte, claimsPtr interface{}, validators ...TokenValidator) error {
verifiedToken, err := VerifyWithHeaderValidator(nil, nil, token, keys.ValidateHeader, validators...)
if err != nil {
return err
}
return verifiedToken.Claims(&claimsPtr)
}