forked from pascaldekloe/jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.go
More file actions
317 lines (278 loc) · 8.44 KB
/
jwt.go
File metadata and controls
317 lines (278 loc) · 8.44 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Package jwt implements “JSON Web Token (JWT)” RFC 7519.
// Signatures only; no unsecured nor encrypted tokens.
package jwt
import (
"crypto"
"encoding/base64"
"encoding/json"
"errors"
"strconv"
"time"
)
// Algorithm Identification Tokens
const (
EdDSA = "EdDSA" // EdDSA signature algorithms
ES256 = "ES256" // ECDSA using P-256 and SHA-256
ES384 = "ES384" // ECDSA using P-384 and SHA-384
ES512 = "ES512" // ECDSA using P-521 and SHA-512
HS256 = "HS256" // HMAC using SHA-256
HS384 = "HS384" // HMAC using SHA-384
HS512 = "HS512" // HMAC using SHA-512
PS256 = "PS256" // RSASSA-PSS using SHA-256 and MGF1 with SHA-256
PS384 = "PS384" // RSASSA-PSS using SHA-384 and MGF1 with SHA-384
PS512 = "PS512" // RSASSA-PSS using SHA-512 and MGF1 with SHA-512
RS256 = "RS256" // RSASSA-PKCS1-v1_5 using SHA-256
RS384 = "RS384" // RSASSA-PKCS1-v1_5 using SHA-384
RS512 = "RS512" // RSASSA-PKCS1-v1_5 using SHA-512
)
// Algorithm support is configured with hash registrations.
var (
ECDSAAlgs = map[string]crypto.Hash{
ES256: crypto.SHA256,
ES384: crypto.SHA384,
ES512: crypto.SHA512,
}
HMACAlgs = map[string]crypto.Hash{
HS256: crypto.SHA256,
HS384: crypto.SHA384,
HS512: crypto.SHA512,
}
RSAAlgs = map[string]crypto.Hash{
PS256: crypto.SHA256,
PS384: crypto.SHA384,
PS512: crypto.SHA512,
RS256: crypto.SHA256,
RS384: crypto.SHA384,
RS512: crypto.SHA512,
}
)
// See crypto.Hash.Available.
var errHashLink = errors.New("jwt: hash function not linked into binary")
func hashLookup(alg string, algs map[string]crypto.Hash) (crypto.Hash, error) {
// availability check
hash, ok := algs[alg]
if !ok {
return 0, AlgError(alg)
}
if !hash.Available() {
return 0, errHashLink
}
return hash, nil
}
// AlgError signals that the specified algorithm is not in use.
type AlgError string
// Error honors the error interface.
func (e AlgError) Error() string {
return "jwt: algorithm " + strconv.Quote(string(e)) + " not in use"
}
// ErrNoSecret protects against programming and configuration mistakes.
var errNoSecret = errors.New("jwt: empty secret rejected")
var encoding = base64.RawURLEncoding
// Standard (IANA registered) claim names.
const (
issuer = "iss"
subject = "sub"
audience = "aud"
expires = "exp"
notBefore = "nbf"
issued = "iat"
id = "jti"
)
// Registered “JSON Web Token Claims” is a subset of the IANA registration.
// See <https://www.iana.org/assignments/jwt/claims.csv> for the full listing.
//
// Each field is optional—there are no required claims. The string values are
// case sensitive.
type Registered struct {
// Issuer identifies the principal that issued the JWT.
Issuer string `json:"iss,omitempty"`
// Subject identifies the principal that is the subject of the JWT.
Subject string `json:"sub,omitempty"`
// Audiences identifies the recipients that the JWT is intended for.
Audiences []string `json:"aud,omitempty"`
// Expires identifies the expiration time on or after which the JWT
// must not be accepted for processing.
Expires *NumericTime `json:"exp,omitempty"`
// NotBefore identifies the time before which the JWT must not be
// accepted for processing.
NotBefore *NumericTime `json:"nbf,omitempty"`
// Issued identifies the time at which the JWT was issued.
Issued *NumericTime `json:"iat,omitempty"`
// ID provides a unique identifier for the JWT.
ID string `json:"jti,omitempty"`
}
// AcceptAudience verifies the applicability of the audience identified with
// stringOrURI. Any stringOrURI is accepted on absence of the audience claim.
func (r *Registered) AcceptAudience(stringOrURI string) bool {
for _, a := range r.Audiences {
if stringOrURI == a {
return true
}
}
return len(r.Audiences) == 0
}
// Claims are the (signed) statements of a JWT.
type Claims struct {
// Registered field values take precedence.
Registered
// Set maps claims by name, for usecases beyond the Registered fields.
// The Sign methods copy each non-zero Registered value into Set when
// the map is not nil. The Check methods map claims in Set if the name
// doesn't match any of the Registered, or if the data type won't fit.
// Entries are treated conform the encoding/json package.
//
// bool, for JSON booleans
// float64, for JSON numbers
// string, for JSON strings
// []interface{}, for JSON arrays
// map[string]interface{}, for JSON objects
// nil for JSON null
//
Set map[string]interface{}
// Raw encoding as is within the token. This field is read-only.
Raw json.RawMessage
// “The "kid" (key ID) Header Parameter is a hint indicating which key
// was used to secure the JWS. This parameter allows originators to
// explicitly signal a change of key to recipients. The structure of
// the "kid" value is unspecified. Its value MUST be a case-sensitive
// string. Use of this Header Parameter is OPTIONAL.”
// — “JSON Web Signature (JWS)” RFC 7515, subsection 4.1.4
KeyID string
}
// Sync updates the Raw field. When the Set field is not nil,
// then all non-zero Registered values are copied into the map.
func (c *Claims) sync() error {
var payload interface{}
if c.Set == nil {
payload = &c.Registered
} else {
payload = c.Set
if c.Issuer != "" {
c.Set[issuer] = c.Issuer
}
if c.Subject != "" {
c.Set[subject] = c.Subject
}
switch len(c.Audiences) {
case 0:
break
case 1: // single string
c.Set[audience] = c.Audiences[0]
default:
array := make([]interface{}, len(c.Audiences))
for i, s := range c.Audiences {
array[i] = s
}
c.Set[audience] = array
}
if c.Expires != nil {
c.Set[expires] = float64(*c.Expires)
}
if c.NotBefore != nil {
c.Set[notBefore] = float64(*c.NotBefore)
}
if c.Issued != nil {
c.Set[issued] = float64(*c.Issued)
}
if c.ID != "" {
c.Set[id] = c.ID
}
}
bytes, err := json.Marshal(payload)
if err != nil {
return err
}
c.Raw = json.RawMessage(bytes)
return nil
}
// Valid returns whether the claims set may be accepted for processing at the
// given moment in time. If time is zero, then Valid returns whether there are
// any time constraints at all.
func (c *Claims) Valid(t time.Time) bool {
exp, expOK := c.Number(expires)
nbf, nbfOK := c.Number(notBefore)
n := NewNumericTime(t)
if n == nil {
return !expOK && !nbfOK
}
f := float64(*n)
return (!expOK || exp > f) && (!nbfOK || nbf <= f)
}
// String returns the claim when present and if the representation is a JSON string.
func (c *Claims) String(name string) (value string, ok bool) {
// try Registered first
switch name {
case issuer:
value = c.Issuer
case subject:
value = c.Subject
case audience:
if len(c.Audiences) == 1 {
return c.Audiences[0], true
}
if len(c.Audiences) != 0 {
return "", false
}
case id:
value = c.ID
}
if value != "" {
return value, true
}
// fallback
value, ok = c.Set[name].(string)
return
}
// Number returns the claim when present and if the representation is a JSON number.
func (c *Claims) Number(name string) (value float64, ok bool) {
// try Registered first
switch name {
case expires:
if c.Expires != nil {
return float64(*c.Expires), true
}
case notBefore:
if c.NotBefore != nil {
return float64(*c.NotBefore), true
}
case issued:
if c.Issued != nil {
return float64(*c.Issued), true
}
}
// fallback
value, ok = c.Set[name].(float64)
return
}
// NumericTime implements NumericDate: “A JSON numeric value representing
// the number of seconds from 1970-01-01T00:00:00Z UTC until the specified
// UTC date/time, ignoring leap seconds.”
type NumericTime float64
// NewNumericTime returns the the corresponding representation with nil for the
// zero value. Do t.Round(time.Second) for slighly smaller token production and
// compatibility. See the bugs section for details.
func NewNumericTime(t time.Time) *NumericTime {
if t.IsZero() {
return nil
}
// BUG(pascaldekloe): Some broken implementations fail to parse tokens
// with fractions in Registered.Expires, .NotBefore or .Issued. Round to
// seconds—like NewNumericDate(time.Now().Round(time.Seconds))—for
// compatibility.
n := NumericTime(float64(t.UnixNano()) / 1e9)
return &n
}
// Time returns the Go mapping with the zero value for nil.
func (n *NumericTime) Time() time.Time {
if n == nil {
return time.Time{}
}
return time.Unix(0, int64(float64(*n)*float64(time.Second))).UTC()
}
// String returns the ISO representation or the empty string for nil.
func (n *NumericTime) String() string {
if n == nil {
return ""
}
return n.Time().Format(time.RFC3339Nano)
}