jwt

package
v0.0.0-...-488a668 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 25, 2024 License: BSD-3-Clause Imports: 13 Imported by: 0

README

Package jwt

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted. JWTs are always represented using the JWS Compact Serialization or the JWE Compact Serialization.

In its compact form, a JSON Web Token consist of three parts separated by dots.

Header.Payload.Signature

The signature is used to verify the message wasn't changed along the way (i.e., integrity), and in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is (i.e., provenance).

Claims

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the JWT holder) and additional data. There are three types of claims: registered, public, and private.

Registered claims are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims.

Public claims can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.

Private claims are the custom claims created to share information between parties that agree on using them and are neither registered nor public claims.

More information: https://tools.ietf.org/html/rfc7519

Documentation

Overview

Package jwt provides a JSON Web Token (JWT) implementation as specified by RFC-7519.

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted. JWTs are always represented using the JWS Compact Serialization or the JWE Compact Serialization.

In its compact form, a JSON Web Token consist of three parts separated by dots.

Header.Payload.Signature

The signature is used to verify the message wasn't changed along the way (i.e., integrity), and in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is (i.e., provenance).

Claims

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the JWT holder) and additional data. There are three types of claims: registered, public, and private.

Registered claims are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims.

Public claims can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.

Private claims are the custom claims created to share information between parties that agree on using them and are neither registered nor public claims.

More information: https://tools.ietf.org/html/rfc7519

Index

Constants

View Source
const (
	// ErrAudValidation is the error for an invalid "aud" claim.
	ErrAudValidation = "aud claim is invalid"
	// ErrExpValidation is the error for an invalid "exp" claim.
	ErrExpValidation = "exp claim is invalid"
	// ErrIatValidation is the error for an invalid "iat" claim.
	ErrIatValidation = "iat claim is invalid"
	// ErrIssValidation is the error for an invalid "iss" claim.
	ErrIssValidation = "iss claim is invalid"
	// ErrJtiValidation is the error for an invalid "jti" claim.
	ErrJtiValidation = "jti claim is invalid"
	// ErrNbfValidation is the error for an invalid "nbf" claim.
	ErrNbfValidation = "nbf claim is invalid"
	// ErrSubValidation is the error for an invalid "sub" claim.
	ErrSubValidation = "sub claim is invalid"
	// ErrAlgValidation is the error for an invalid "alg" header.
	ErrAlgValidation = "alg header is invalid"
	// ErrCtyValidation is the error for an invalid "cty" header.
	ErrCtyValidation = "cty header is invalid"
	// ErrAmrValidation is the error for an invalid "amr" claim.
	ErrAmrValidation = "amr claim is invalid"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Check

type Check func(token *Token) error

Check functions allow to execute verifications against a JWT instance.

func AlgorithmCheck

func AlgorithmCheck(alg string) Check

AlgorithmCheck validates the "alg" header.

func AudienceCheck

func AudienceCheck(aud []string) Check

AudienceCheck validates the "aud" claim. It checks if at least one of the audiences in the JWT payload is listed in aud.

func ContentTypeCheck

func ContentTypeCheck(cty string) Check

ContentTypeCheck validates the "cty" header.

func ExpirationTimeCheck

func ExpirationTimeCheck(now time.Time, validateZero bool) Check

ExpirationTimeCheck validates the "exp" claim.

func IDCheck

func IDCheck(jti string) Check

IDCheck validates the "jti" claim.

func IssuedAtCheck

func IssuedAtCheck(now time.Time) Check

IssuedAtCheck validates the "iat" claim.

func IssuerCheck

func IssuerCheck(iss string) Check

IssuerCheck validates the "iss" claim.

func NotBeforeCheck

func NotBeforeCheck(now time.Time) Check

NotBeforeCheck validates the "nbf" claim.

func SubjectCheck

func SubjectCheck(sub string) Check

SubjectCheck validates the "sub" claim.

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator instances can be used to generate new tokens and validate the ones previously issued.

func NewGenerator

func NewGenerator(issuer string, opts ...GeneratorOption) (*Generator, error)

NewGenerator returns a new generator instance ready to be used. A provider offers a JWT generation and validation interface. The provided `issuer` value will be included in the `issuer` header for all generated tokens.

func (*Generator) AddKey

func (g *Generator) AddKey(keys ...jwk.Key) error

AddKey will register a new cryptographic key with the token generator. If the identifier is already used the method will return an error.

func (*Generator) ExportKeys

func (g *Generator) ExportKeys(safe bool) jwk.Set

ExportKeys returns the cryptographic keys available on the generator as a portable JWK set. When `safe` is true, the private key information won't be included in the exported data. https://www.rfc-editor.org/rfc/rfc7517.html#section-5

func (*Generator) IsSupported

func (g *Generator) IsSupported(alg jwa.Alg) bool

IsSupported ensures the provided JWT method is supported by the generator based on the keys available.

func (*Generator) Issue

func (g *Generator) Issue(keyID string, params *TokenParameters) (*Token, error)

Issue a new token signed using the selected key and based on the provided configuration parameters. Pass "none" as the `keyID` to issue a jwa.NONE token, if supported by the generator.

func (*Generator) Name

func (g *Generator) Name() string

Name returns the generator identifier. This identifier will be set in the "iss" registered claim for all generated tokens.

func (*Generator) RemoveKey

func (g *Generator) RemoveKey(id string)

RemoveKey can be used to decommission an existing cryptographic key from the token generator. If the identifier doesn't exist, calling this method is a no-op.

func (*Generator) Validate

func (g *Generator) Validate(token string, checks ...Check) error

Validate a previously generated token instance.

  1. Is the string a valid JWT?
  2. Is 'alg' supported by the generator?
  3. Is the digital signature valid?
  4. Run all provided checks

type GeneratorOption

type GeneratorOption func(g *Generator) error

GeneratorOption elements provide a functional-style configuration mechanism for token generators.

func WithKey

func WithKey(k jwk.Key) GeneratorOption

WithKey registers a cryptographic key on the generator instance.

func WithKeySet

func WithKeySet(set jwk.Set) GeneratorOption

WithKeySet registers a JWK set of keys on the generator instance.

func WithSupportForNone

func WithSupportForNone() GeneratorOption

WithSupportForNone enables support for the 'NONE' JWA algorithm; this is disabled by default. 'NONE' tokens are considered insecure.

type Header struct {
	// Declare the media type of this complete JWT.
	Type string `json:"typ,omitempty"`

	// Specify the cryptographic algorithm used to generate the JWT.
	Algorithm string `json:"alg,omitempty"`

	// Used to convey structural information about the JWT.
	ContentType string `json:"cty,omitempty"`

	// An optional identifier for the cryptographic key used to generate the JWT.
	KeyID string `json:"kid,omitempty"`
}

Header is based on the JWT specification from RFC-7519.

typ (type)         - media type
alg (algorithm)    - cryptographic algorithm used to generate the token
cty (content type) - used to convey structural information about the token
kid (key id)       - identifier for the cryptographic key used to sign the token

type RegisteredClaims

type RegisteredClaims struct {
	// The principal that issued the JWT.
	Issuer string `json:"iss,omitempty"`

	// The principal that is the subject of the JWT.
	Subject string `json:"sub,omitempty"`

	// The recipients that the JWT is intended for.
	Audience []string `json:"aud,omitempty"`

	// The expiration time on or after which the JWT MUST NOT be accepted for processing.
	ExpirationTime int64 `json:"exp,omitempty"`

	// The time before which the JWT MUST NOT be accepted for processing.
	NotBefore int64 `json:"nbf,omitempty"`

	// The time at which the JWT was issued.
	IssuedAt int64 `json:"iat,omitempty"`

	// Unique identifier for the JWT.
	JTI string `json:"jti,omitempty"`
}

RegisteredClaims for the JWT payload section according to the RFC-7519.

iss (issuer)      - identifies the principal that issued the JWT
sub (subject)     - identifies the principal that is the subject of the JWT
aud (audience)    - identifies the recipients that the JWT is intended for
exp (expiration)  - identifies the time on or after which the JWT MUST NOT be accepted
nbf (not before)  - identifies the time before which the JWT MUST NOT be accepted
iat (issued at)   - identifies the time at which the JWT was issued
jti (JWT ID)      - provides a unique identifier for the JWT

More information: https://tools.ietf.org/html/rfc7519#section-4.1

type Token

type Token struct {
	// contains filtered or unexported fields
}

Token represents a specific JWT token instance.

func Parse

func Parse(token string) (*Token, error)

Parse returns a functional token instance from its compact string representation.

func (*Token) Bytes

func (t *Token) Bytes() []byte

Bytes returns the binary contents of a properly encoded and formatted textual representation of the token.

func (*Token) Decode

func (t *Token) Decode(v interface{}) error

Decode will load the token payload segment (i.e., claims content) into the provided holder.

func (*Token) Get

func (t *Token) Get(jp string) (interface{}, error)

Get a single claim from the token's payload. The provided `jp` value MUST be a valid JSON pointer as defined by RFC-6901. For example:

  • "/iss"
  • "/scope"
  • "/custom/list/0"

https://datatracker.ietf.org/doc/html/rfc6901

func (*Token) Header

func (t *Token) Header() Header

Header segment of the token instance.

func (*Token) RegisteredClaims

func (t *Token) RegisteredClaims() (RegisteredClaims, error)

RegisteredClaims returns the "registered" claims section of the token.

func (*Token) String

func (t *Token) String() string

String returns a properly encoded and formatted textual representation of the token.

func (*Token) Validate

func (t *Token) Validate(checks ...Check) error

Validate will apply the provided validator functions to the token instance.

type TokenParameters

type TokenParameters struct {
	// The principal that is the subject of the JWT, required.
	Subject string

	// Recipients that the JWT is intended for, required.
	Audience []string

	// Cryptographic method used for the token.
	// Optional when generating a new token, it will be automatically
	// set to the proper value based on the key used to sign the
	// token or to "NONE".
	Method string

	// Specify a custom content identifier in the JWT header.
	// Optional when generating a new token, not set by default.
	ContentType string

	// Set an expiration value for the JWT.
	// A duration string is a signed sequence of decimal numbers, each with optional
	// fraction and a unit suffix, such as "300ms", "1.5h" or "2h45m". Valid time units
	// are: "ns", "us" (or "µs"), "ms", "s", "m", "h"
	// Optional when generating a new token, defaults to "720h".
	Expiration string

	// The time before which the JWT MUST NOT be accepted for processing.
	// A duration string is a signed sequence of decimal numbers, each with optional
	// fraction and a unit suffix, such as "300ms", "1.5h" or "2h45m". Valid time units
	// are: "ns", "us" (or "µs"), "ms", "s", "m", "h"
	// Optional when generating a new token, defaults to "0s".
	NotBefore string

	// Identifier for the token instance, MUST be unique.
	// Optional when generating a new token, defaults to a random UUID v4.
	UniqueIdentifier string

	// Additional public and private claims to be added/expected on the JWT payload,
	// optional. If any key in the custom claims conflicts with an existing registered
	// claim, the latter will take precedence and override the custom value.
	CustomClaims interface{}
	// contains filtered or unexported fields
}

TokenParameters define the settings used to create and validate tokens.

func (*TokenParameters) GetChecks

func (tp *TokenParameters) GetChecks() []Check

GetChecks return a collection of standard validations based on the parameters.

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator instances can be used when tokens need to be validated but issuing is not possible or desired. For example when retrieving the server's JWK key set including only public keys.

func NewValidator

func NewValidator(opts ...ValidatorOption) (*Validator, error)

NewValidator returns a new token validator instance ready to be used.

func (*Validator) Validate

func (v *Validator) Validate(token string, checks ...Check) error

Validate a previously generated token instance.

  1. Is the string a valid JWT?
  2. Is 'alg' supported by the generator?
  3. Is the digital signature valid?
  4. Run all provided checks

type ValidatorOption

type ValidatorOption func(v *Validator) error

ValidatorOption elements provide a functional-style configuration mechanism for token validators.

func WithValidationKeys

func WithValidationKeys(set jwk.Set) ValidatorOption

WithValidationKeys registers the keys provided in the JWK set to be used for token validation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL