github.com/nats-io/jwt/v2@v2.5.6/v1compat/genericlaims.go (about)

     1  /*
     2   * Copyright 2018 The NATS Authors
     3   * Licensed under the Apache License, Version 2.0 (the "License");
     4   * you may not use this file except in compliance with the License.
     5   * You may obtain a copy of the License at
     6   *
     7   * http://www.apache.org/licenses/LICENSE-2.0
     8   *
     9   * Unless required by applicable law or agreed to in writing, software
    10   * distributed under the License is distributed on an "AS IS" BASIS,
    11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12   * See the License for the specific language governing permissions and
    13   * limitations under the License.
    14   */
    15  
    16  package jwt
    17  
    18  import "github.com/nats-io/nkeys"
    19  
    20  // GenericClaims can be used to read a JWT as a map for any non-generic fields
    21  type GenericClaims struct {
    22  	ClaimsData
    23  	Data map[string]interface{} `json:"nats,omitempty"`
    24  }
    25  
    26  // NewGenericClaims creates a map-based Claims
    27  func NewGenericClaims(subject string) *GenericClaims {
    28  	if subject == "" {
    29  		return nil
    30  	}
    31  	c := GenericClaims{}
    32  	c.Subject = subject
    33  	c.Data = make(map[string]interface{})
    34  	return &c
    35  }
    36  
    37  // DecodeGeneric takes a JWT string and decodes it into a ClaimsData and map
    38  func DecodeGeneric(token string) (*GenericClaims, error) {
    39  	v := GenericClaims{}
    40  	if err := Decode(token, &v); err != nil {
    41  		return nil, err
    42  	}
    43  	return &v, nil
    44  }
    45  
    46  // Claims returns the standard part of the generic claim
    47  func (gc *GenericClaims) Claims() *ClaimsData {
    48  	return &gc.ClaimsData
    49  }
    50  
    51  // Payload returns the custom part of the claims data
    52  func (gc *GenericClaims) Payload() interface{} {
    53  	return &gc.Data
    54  }
    55  
    56  // Encode takes a generic claims and creates a JWT string
    57  func (gc *GenericClaims) Encode(pair nkeys.KeyPair) (string, error) {
    58  	return gc.ClaimsData.Encode(pair, gc)
    59  }
    60  
    61  // Validate checks the generic part of the claims data
    62  func (gc *GenericClaims) Validate(vr *ValidationResults) {
    63  	gc.ClaimsData.Validate(vr)
    64  }
    65  
    66  func (gc *GenericClaims) String() string {
    67  	return gc.ClaimsData.String(gc)
    68  }
    69  
    70  // ExpectedPrefixes returns the types allowed to encode a generic JWT, which is nil for all
    71  func (gc *GenericClaims) ExpectedPrefixes() []nkeys.PrefixByte {
    72  	return nil
    73  }