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 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
|
// Code generated by tools/cmd/genjwt/main.go. DO NOT EDIT.
package jwt
import (
"bytes"
"context"
"fmt"
"sort"
"sync"
"time"
"github.com/lestrrat-go/iter/mapiter"
"github.com/lestrrat-go/jwx/v2/internal/base64"
"github.com/lestrrat-go/jwx/v2/internal/iter"
"github.com/lestrrat-go/jwx/v2/internal/json"
"github.com/lestrrat-go/jwx/v2/internal/pool"
"github.com/lestrrat-go/jwx/v2/jwt/internal/types"
)
const (
AudienceKey = "aud"
ExpirationKey = "exp"
IssuedAtKey = "iat"
IssuerKey = "iss"
JwtIDKey = "jti"
NotBeforeKey = "nbf"
SubjectKey = "sub"
)
// Token represents a generic JWT token.
// which are type-aware (to an extent). Other claims may be accessed via the `Get`/`Set`
// methods but their types are not taken into consideration at all. If you have non-standard
// claims that you must frequently access, consider creating accessors functions
// like the following
//
// func SetFoo(tok jwt.Token) error
// func GetFoo(tok jwt.Token) (*Customtyp, error)
//
// Embedding jwt.Token into another struct is not recommended, because
// jwt.Token needs to handle private claims, and this really does not
// work well when it is embedded in other structure
type Token interface {
// Audience returns the value for "aud" field of the token
Audience() []string
// Expiration returns the value for "exp" field of the token
Expiration() time.Time
// IssuedAt returns the value for "iat" field of the token
IssuedAt() time.Time
// Issuer returns the value for "iss" field of the token
Issuer() string
// JwtID returns the value for "jti" field of the token
JwtID() string
// NotBefore returns the value for "nbf" field of the token
NotBefore() time.Time
// Subject returns the value for "sub" field of the token
Subject() string
// PrivateClaims return the entire set of fields (claims) in the token
// *other* than the pre-defined fields such as `iss`, `nbf`, `iat`, etc.
PrivateClaims() map[string]interface{}
// Get returns the value of the corresponding field in the token, such as
// `nbf`, `exp`, `iat`, and other user-defined fields. If the field does not
// exist in the token, the second return value will be `false`
//
// If you need to access fields like `alg`, `kid`, `jku`, etc, you need
// to access the corresponding fields in the JWS/JWE message. For this,
// you will need to access them by directly parsing the payload using
// `jws.Parse` and `jwe.Parse`
Get(string) (interface{}, bool)
// Set assigns a value to the corresponding field in the token. Some
// pre-defined fields such as `nbf`, `iat`, `iss` need their values to
// be of a specific type. See the other getter methods in this interface
// for the types of each of these fields
Set(string, interface{}) error
Remove(string) error
// Options returns the per-token options associated with this token.
// The options set value will be copied when the token is cloned via `Clone()`
// but it will not survive when the token goes through marshaling/unmarshaling
// such as `json.Marshal` and `json.Unmarshal`
Options() *TokenOptionSet
Clone() (Token, error)
Iterate(context.Context) Iterator
Walk(context.Context, Visitor) error
AsMap(context.Context) (map[string]interface{}, error)
}
type stdToken struct {
mu *sync.RWMutex
dc DecodeCtx // per-object context for decoding
options TokenOptionSet // per-object option
audience types.StringList // https://tools.ietf.org/html/rfc7519#section-4.1.3
expiration *types.NumericDate // https://tools.ietf.org/html/rfc7519#section-4.1.4
issuedAt *types.NumericDate // https://tools.ietf.org/html/rfc7519#section-4.1.6
issuer *string // https://tools.ietf.org/html/rfc7519#section-4.1.1
jwtID *string // https://tools.ietf.org/html/rfc7519#section-4.1.7
notBefore *types.NumericDate // https://tools.ietf.org/html/rfc7519#section-4.1.5
subject *string // https://tools.ietf.org/html/rfc7519#section-4.1.2
privateClaims map[string]interface{}
}
// New creates a standard token, with minimal knowledge of
// possible claims. Standard claims include"aud", "exp", "iat", "iss", "jti", "nbf" and "sub".
// Convenience accessors are provided for these standard claims
func New() Token {
return &stdToken{
mu: &sync.RWMutex{},
privateClaims: make(map[string]interface{}),
options: DefaultOptionSet(),
}
}
func (t *stdToken) Options() *TokenOptionSet {
return &t.options
}
func (t *stdToken) Get(name string) (interface{}, bool) {
t.mu.RLock()
defer t.mu.RUnlock()
switch name {
case AudienceKey:
if t.audience == nil {
return nil, false
}
v := t.audience.Get()
return v, true
case ExpirationKey:
if t.expiration == nil {
return nil, false
}
v := t.expiration.Get()
return v, true
case IssuedAtKey:
if t.issuedAt == nil {
return nil, false
}
v := t.issuedAt.Get()
return v, true
case IssuerKey:
if t.issuer == nil {
return nil, false
}
v := *(t.issuer)
return v, true
case JwtIDKey:
if t.jwtID == nil {
return nil, false
}
v := *(t.jwtID)
return v, true
case NotBeforeKey:
if t.notBefore == nil {
return nil, false
}
v := t.notBefore.Get()
return v, true
case SubjectKey:
if t.subject == nil {
return nil, false
}
v := *(t.subject)
return v, true
default:
v, ok := t.privateClaims[name]
return v, ok
}
}
func (t *stdToken) Remove(key string) error {
t.mu.Lock()
defer t.mu.Unlock()
switch key {
case AudienceKey:
t.audience = nil
case ExpirationKey:
t.expiration = nil
case IssuedAtKey:
t.issuedAt = nil
case IssuerKey:
t.issuer = nil
case JwtIDKey:
t.jwtID = nil
case NotBeforeKey:
t.notBefore = nil
case SubjectKey:
t.subject = nil
default:
delete(t.privateClaims, key)
}
return nil
}
func (t *stdToken) Set(name string, value interface{}) error {
t.mu.Lock()
defer t.mu.Unlock()
return t.setNoLock(name, value)
}
func (t *stdToken) DecodeCtx() DecodeCtx {
t.mu.RLock()
defer t.mu.RUnlock()
return t.dc
}
func (t *stdToken) SetDecodeCtx(v DecodeCtx) {
t.mu.Lock()
defer t.mu.Unlock()
t.dc = v
}
func (t *stdToken) setNoLock(name string, value interface{}) error {
switch name {
case AudienceKey:
var acceptor types.StringList
if err := acceptor.Accept(value); err != nil {
return fmt.Errorf(`invalid value for %s key: %w`, AudienceKey, err)
}
t.audience = acceptor
return nil
case ExpirationKey:
var acceptor types.NumericDate
if err := acceptor.Accept(value); err != nil {
return fmt.Errorf(`invalid value for %s key: %w`, ExpirationKey, err)
}
t.expiration = &acceptor
return nil
case IssuedAtKey:
var acceptor types.NumericDate
if err := acceptor.Accept(value); err != nil {
return fmt.Errorf(`invalid value for %s key: %w`, IssuedAtKey, err)
}
t.issuedAt = &acceptor
return nil
case IssuerKey:
if v, ok := value.(string); ok {
t.issuer = &v
return nil
}
return fmt.Errorf(`invalid value for %s key: %T`, IssuerKey, value)
case JwtIDKey:
if v, ok := value.(string); ok {
t.jwtID = &v
return nil
}
return fmt.Errorf(`invalid value for %s key: %T`, JwtIDKey, value)
case NotBeforeKey:
var acceptor types.NumericDate
if err := acceptor.Accept(value); err != nil {
return fmt.Errorf(`invalid value for %s key: %w`, NotBeforeKey, err)
}
t.notBefore = &acceptor
return nil
case SubjectKey:
if v, ok := value.(string); ok {
t.subject = &v
return nil
}
return fmt.Errorf(`invalid value for %s key: %T`, SubjectKey, value)
default:
if t.privateClaims == nil {
t.privateClaims = map[string]interface{}{}
}
t.privateClaims[name] = value
}
return nil
}
func (t *stdToken) Audience() []string {
t.mu.RLock()
defer t.mu.RUnlock()
if t.audience != nil {
return t.audience.Get()
}
return nil
}
func (t *stdToken) Expiration() time.Time {
t.mu.RLock()
defer t.mu.RUnlock()
if t.expiration != nil {
return t.expiration.Get()
}
return time.Time{}
}
func (t *stdToken) IssuedAt() time.Time {
t.mu.RLock()
defer t.mu.RUnlock()
if t.issuedAt != nil {
return t.issuedAt.Get()
}
return time.Time{}
}
func (t *stdToken) Issuer() string {
t.mu.RLock()
defer t.mu.RUnlock()
if t.issuer != nil {
return *(t.issuer)
}
return ""
}
func (t *stdToken) JwtID() string {
t.mu.RLock()
defer t.mu.RUnlock()
if t.jwtID != nil {
return *(t.jwtID)
}
return ""
}
func (t *stdToken) NotBefore() time.Time {
t.mu.RLock()
defer t.mu.RUnlock()
if t.notBefore != nil {
return t.notBefore.Get()
}
return time.Time{}
}
func (t *stdToken) Subject() string {
t.mu.RLock()
defer t.mu.RUnlock()
if t.subject != nil {
return *(t.subject)
}
return ""
}
func (t *stdToken) PrivateClaims() map[string]interface{} {
t.mu.RLock()
defer t.mu.RUnlock()
return t.privateClaims
}
func (t *stdToken) makePairs() []*ClaimPair {
t.mu.RLock()
defer t.mu.RUnlock()
pairs := make([]*ClaimPair, 0, 7)
if t.audience != nil {
v := t.audience.Get()
pairs = append(pairs, &ClaimPair{Key: AudienceKey, Value: v})
}
if t.expiration != nil {
v := t.expiration.Get()
pairs = append(pairs, &ClaimPair{Key: ExpirationKey, Value: v})
}
if t.issuedAt != nil {
v := t.issuedAt.Get()
pairs = append(pairs, &ClaimPair{Key: IssuedAtKey, Value: v})
}
if t.issuer != nil {
v := *(t.issuer)
pairs = append(pairs, &ClaimPair{Key: IssuerKey, Value: v})
}
if t.jwtID != nil {
v := *(t.jwtID)
pairs = append(pairs, &ClaimPair{Key: JwtIDKey, Value: v})
}
if t.notBefore != nil {
v := t.notBefore.Get()
pairs = append(pairs, &ClaimPair{Key: NotBeforeKey, Value: v})
}
if t.subject != nil {
v := *(t.subject)
pairs = append(pairs, &ClaimPair{Key: SubjectKey, Value: v})
}
for k, v := range t.privateClaims {
pairs = append(pairs, &ClaimPair{Key: k, Value: v})
}
sort.Slice(pairs, func(i, j int) bool {
return pairs[i].Key.(string) < pairs[j].Key.(string)
})
return pairs
}
func (t *stdToken) UnmarshalJSON(buf []byte) error {
t.mu.Lock()
defer t.mu.Unlock()
t.audience = nil
t.expiration = nil
t.issuedAt = nil
t.issuer = nil
t.jwtID = nil
t.notBefore = nil
t.subject = nil
dec := json.NewDecoder(bytes.NewReader(buf))
LOOP:
for {
tok, err := dec.Token()
if err != nil {
return fmt.Errorf(`error reading token: %w`, err)
}
switch tok := tok.(type) {
case json.Delim:
// Assuming we're doing everything correctly, we should ONLY
// get either '{' or '}' here.
if tok == '}' { // End of object
break LOOP
} else if tok != '{' {
return fmt.Errorf(`expected '{', but got '%c'`, tok)
}
case string: // Objects can only have string keys
switch tok {
case AudienceKey:
var decoded types.StringList
if err := dec.Decode(&decoded); err != nil {
return fmt.Errorf(`failed to decode value for key %s: %w`, AudienceKey, err)
}
t.audience = decoded
case ExpirationKey:
var decoded types.NumericDate
if err := dec.Decode(&decoded); err != nil {
return fmt.Errorf(`failed to decode value for key %s: %w`, ExpirationKey, err)
}
t.expiration = &decoded
case IssuedAtKey:
var decoded types.NumericDate
if err := dec.Decode(&decoded); err != nil {
return fmt.Errorf(`failed to decode value for key %s: %w`, IssuedAtKey, err)
}
t.issuedAt = &decoded
case IssuerKey:
if err := json.AssignNextStringToken(&t.issuer, dec); err != nil {
return fmt.Errorf(`failed to decode value for key %s: %w`, IssuerKey, err)
}
case JwtIDKey:
if err := json.AssignNextStringToken(&t.jwtID, dec); err != nil {
return fmt.Errorf(`failed to decode value for key %s: %w`, JwtIDKey, err)
}
case NotBeforeKey:
var decoded types.NumericDate
if err := dec.Decode(&decoded); err != nil {
return fmt.Errorf(`failed to decode value for key %s: %w`, NotBeforeKey, err)
}
t.notBefore = &decoded
case SubjectKey:
if err := json.AssignNextStringToken(&t.subject, dec); err != nil {
return fmt.Errorf(`failed to decode value for key %s: %w`, SubjectKey, err)
}
default:
if dc := t.dc; dc != nil {
if localReg := dc.Registry(); localReg != nil {
decoded, err := localReg.Decode(dec, tok)
if err == nil {
t.setNoLock(tok, decoded)
continue
}
}
}
decoded, err := registry.Decode(dec, tok)
if err == nil {
t.setNoLock(tok, decoded)
continue
}
return fmt.Errorf(`could not decode field %s: %w`, tok, err)
}
default:
return fmt.Errorf(`invalid token %T`, tok)
}
}
return nil
}
func (t stdToken) MarshalJSON() ([]byte, error) {
buf := pool.GetBytesBuffer()
defer pool.ReleaseBytesBuffer(buf)
buf.WriteByte('{')
enc := json.NewEncoder(buf)
for i, pair := range t.makePairs() {
f := pair.Key.(string)
if i > 0 {
buf.WriteByte(',')
}
buf.WriteRune('"')
buf.WriteString(f)
buf.WriteString(`":`)
switch f {
case AudienceKey:
if err := json.EncodeAudience(enc, pair.Value.([]string), t.options.IsEnabled(FlattenAudience)); err != nil {
return nil, fmt.Errorf(`failed to encode "aud": %w`, err)
}
continue
case ExpirationKey, IssuedAtKey, NotBeforeKey:
enc.Encode(pair.Value.(time.Time).Unix())
continue
}
switch v := pair.Value.(type) {
case []byte:
buf.WriteRune('"')
buf.WriteString(base64.EncodeToString(v))
buf.WriteRune('"')
default:
if err := enc.Encode(v); err != nil {
return nil, fmt.Errorf(`failed to marshal field %s: %w`, f, err)
}
buf.Truncate(buf.Len() - 1)
}
}
buf.WriteByte('}')
ret := make([]byte, buf.Len())
copy(ret, buf.Bytes())
return ret, nil
}
func (t *stdToken) Iterate(ctx context.Context) Iterator {
pairs := t.makePairs()
ch := make(chan *ClaimPair, len(pairs))
go func(ctx context.Context, ch chan *ClaimPair, pairs []*ClaimPair) {
defer close(ch)
for _, pair := range pairs {
select {
case <-ctx.Done():
return
case ch <- pair:
}
}
}(ctx, ch, pairs)
return mapiter.New(ch)
}
func (t *stdToken) Walk(ctx context.Context, visitor Visitor) error {
return iter.WalkMap(ctx, t, visitor)
}
func (t *stdToken) AsMap(ctx context.Context) (map[string]interface{}, error) {
return iter.AsMap(ctx, t)
}
|