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
- type Check
- func AlgorithmCheck(alg string) Check
- func AudienceCheck(aud []string) Check
- func ContentTypeCheck(cty string) Check
- func ExpirationTimeCheck(now time.Time, validateZero bool) Check
- func IDCheck(jti string) Check
- func IssuedAtCheck(now time.Time) Check
- func IssuerCheck(iss string) Check
- func NotBeforeCheck(now time.Time) Check
- func SubjectCheck(sub string) Check
- type Generator
- func (g *Generator) AddKey(keys ...jwk.Key) error
- func (g *Generator) ExportKeys(safe bool) jwk.Set
- func (g *Generator) IsSupported(alg jwa.Alg) bool
- func (g *Generator) Issue(keyID string, params *TokenParameters) (*Token, error)
- func (g *Generator) Name() string
- func (g *Generator) RemoveKey(id string)
- func (g *Generator) Validate(token string, checks ...Check) error
- type GeneratorOption
- type Header
- type RegisteredClaims
- type Token
- type TokenParameters
- type Validator
- type ValidatorOption
Constants ¶
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 ¶
Check functions allow to execute verifications against a JWT instance.
func AlgorithmCheck ¶
AlgorithmCheck validates the "alg" header.
func AudienceCheck ¶
AudienceCheck validates the "aud" claim. It checks if at least one of the audiences in the JWT payload is listed in aud.
func ContentTypeCheck ¶
ContentTypeCheck validates the "cty" header.
func ExpirationTimeCheck ¶
ExpirationTimeCheck validates the "exp" claim.
func IssuedAtCheck ¶
IssuedAtCheck validates the "iat" claim.
func NotBeforeCheck ¶
NotBeforeCheck validates the "nbf" 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 ¶
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 ¶
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 ¶
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 ¶
Name returns the generator identifier. This identifier will be set in the "iss" registered claim for all generated tokens.
type GeneratorOption ¶
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 ¶
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 (*Token) Bytes ¶
Bytes returns the binary contents of a properly encoded and formatted textual representation of the token.
func (*Token) Decode ¶
Decode will load the token payload segment (i.e., claims content) into the provided holder.
func (*Token) Get ¶
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"
func (*Token) RegisteredClaims ¶
func (t *Token) RegisteredClaims() (RegisteredClaims, error)
RegisteredClaims returns the "registered" claims section of the token.
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.
type ValidatorOption ¶
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.