jwt

package
v12.2.0-beta7 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2022 License: BSD-3-Clause Imports: 6 Imported by: 36

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBlocked           = jwt.ErrBlocked
	ErrDecrypt           = jwt.ErrDecrypt
	ErrExpected          = jwt.ErrExpected
	ErrExpired           = jwt.ErrExpired
	ErrInvalidKey        = jwt.ErrInvalidKey
	ErrIssuedInTheFuture = jwt.ErrIssuedInTheFuture
	ErrMissing           = jwt.ErrMissing
	ErrMissingKey        = jwt.ErrMissingKey
	ErrNotValidYet       = jwt.ErrNotValidYet
	ErrTokenAlg          = jwt.ErrTokenAlg
	ErrTokenForm         = jwt.ErrTokenForm
	ErrTokenSignature    = jwt.ErrTokenSignature
)

Error values.

View Source
var (
	EdDSA = jwt.EdDSA
	HS256 = jwt.HS256
	HS384 = jwt.HS384
	HS512 = jwt.HS512
	RS256 = jwt.RS256
	RS384 = jwt.RS384
	RS512 = jwt.RS512
	ES256 = jwt.ES256
	ES384 = jwt.ES384
	ES512 = jwt.ES512
	PS256 = jwt.PS256
	PS384 = jwt.PS384
	PS512 = jwt.PS512
)

Signature algorithms.

View Source
var (
	MustLoadHMAC         = jwt.MustLoadHMAC
	LoadHMAC             = jwt.LoadHMAC
	MustLoadRSA          = jwt.MustLoadRSA
	LoadPrivateKeyRSA    = jwt.LoadPrivateKeyRSA
	LoadPublicKeyRSA     = jwt.LoadPublicKeyRSA
	ParsePrivateKeyRSA   = jwt.ParsePrivateKeyRSA
	ParsePublicKeyRSA    = jwt.ParsePublicKeyRSA
	MustLoadECDSA        = jwt.MustLoadECDSA
	LoadPrivateKeyECDSA  = jwt.LoadPrivateKeyECDSA
	LoadPublicKeyECDSA   = jwt.LoadPublicKeyECDSA
	ParsePrivateKeyECDSA = jwt.ParsePrivateKeyECDSA
	ParsePublicKeyECDSA  = jwt.ParsePublicKeyECDSA
	MustLoadEdDSA        = jwt.MustLoadEdDSA
	LoadPrivateKeyEdDSA  = jwt.LoadPrivateKeyEdDSA
	LoadPublicKeyEdDSA   = jwt.LoadPublicKeyEdDSA
	ParsePrivateKeyEdDSA = jwt.ParsePrivateKeyEdDSA
	ParsePublicKeyEdDSA  = jwt.ParsePublicKeyEdDSA
)

Signature algorithm helpers.

View Source
var (
	GCM = jwt.GCM
	// Helper to generate random key,
	// can be used to generate hmac signature key and GCM+AES for testing.
	MustGenerateRandom = jwt.MustGenerateRandom
)

Encryption algorithms.

View Source
var (
	// Leeway adds validation for a leeway expiration time.
	// If the token was not expired then a comparison between
	// this "leeway" and the token's "exp" one is expected to pass instead (now+leeway > exp).
	// Example of use case: disallow tokens that are going to be expired in 3 seconds from now,
	// this is useful to make sure that the token is valid when the when the user fires a database call for example.
	// Usage:
	//  verifiedToken, err := verifier.Verify(..., jwt.Leeway(5*time.Second))
	Leeway = jwt.Leeway
	// MaxAge is a SignOption to set the expiration "exp", "iat" JWT standard claims.
	// Can be passed as last input argument of the `Sign` function.
	//
	// If maxAge > second then sets expiration to the token.
	// It's a helper field to set the "exp" and "iat" claim values.
	// Usage:
	//  signer.Sign(..., jwt.MaxAge(15*time.Minute))
	MaxAge = jwt.MaxAge

	// ID is a shurtcut to set jwt ID on Sign.
	ID = func(id string) jwt.SignOptionFunc {
		return func(c *Claims) {
			c.ID = id
		}
	}
)
View Source
var (
	Verify               = jwt.Verify
	VerifyEncryptedToken = jwt.VerifyEncrypted
	Sign                 = jwt.Sign
	SignEncrypted        = jwt.SignEncrypted
)

Shortcuts for Signing and Verifying.

Functions

func FromHeader

func FromHeader(ctx *context.Context) string

FromHeader is a token extractor. It reads the token from the Authorization request header of form: Authorization: "Bearer {token}".

func FromQuery

func FromQuery(ctx *context.Context) string

FromQuery is a token extractor. It reads the token from the "token" url query parameter.

func Get

func Get(ctx *context.Context) interface{}

Get returns the claims decoded by a verifier.

Types

type Alg

type Alg = jwt.Alg

Alg is the signature algorithm interface alias.

type Blocklist

type Blocklist interface {
	jwt.TokenValidator

	// InvalidateToken should invalidate a verified JWT token.
	InvalidateToken(token []byte, c Claims) error
	// Del should remove a token from the storage.
	Del(key string) error
	// Has should report whether a specific token exists in the storage.
	Has(key string) (bool, error)
	// Count should return the total amount of tokens stored.
	Count() (int64, error)
}

Blocklist should hold and manage invalidated-by-server tokens. The `NewBlocklist` and `NewBlocklistContext` functions returns a memory storage of tokens, it is the internal "blocklist" struct.

The end-developer can implement her/his own blocklist, e.g. a redis one to keep persistence of invalidated tokens on server restarts. and bind to the JWT middleware's Blocklist field.

type Claims

type Claims = jwt.Claims

Claims represents the standard claim values (as specified in RFC 7519).

type ClaimsContextValidator

type ClaimsContextValidator interface {
	Validate(*context.Context) error
}

ClaimsContextValidator same as ClaimsValidator but it accepts a request context which can be used for further checks before validating the incoming token's claims.

type ClaimsValidator

type ClaimsValidator interface {
	Validate() error
}

ClaimsValidator is a special interface which, if the destination claims implements it then the verifier runs its Validate method before return.

type Expected

type Expected = jwt.Expected

Expected is a TokenValidator which performs simple checks between standard claims values.

Usage:

 expecteed := jwt.Expected{
	  Issuer: "my-app",
 }
 verifiedToken, err := verifier.Verify(..., expected)

type SignOption

type SignOption = jwt.SignOption

SignOption used to set signing options at Sign function.

type Signer

type Signer struct {
	Alg Alg
	Key interface{}

	// MaxAge to set "exp" and "iat".
	// Recommended value for access tokens: 15 minutes.
	// Defaults to 0, no limit.
	MaxAge  time.Duration
	Options []SignOption

	Encrypt func([]byte) ([]byte, error)
}

Signer holds common options to sign and generate a token. Its Sign method can be used to generate a token which can be sent to the client. Its NewTokenPair can be used to construct a token pair (access_token, refresh_token).

It does not support JWE, JWK.

func NewSigner

func NewSigner(signatureAlg Alg, signatureKey interface{}, maxAge time.Duration) *Signer

NewSigner accepts the signature algorithm among with its (private or shared) key and the max life time duration of generated tokens and returns a JWT signer. See its Sign method.

Usage:

signer := NewSigner(HS256, secret, 15*time.Minute)
token, err := signer.Sign(userClaims{Username: "kataras"})

func (*Signer) NewTokenPair

func (s *Signer) NewTokenPair(accessClaims interface{}, refreshClaims interface{}, refreshMaxAge time.Duration, accessOpts ...SignOption) (TokenPair, error)

NewTokenPair accepts the access and refresh claims plus the life time duration for the refresh token and generates a new token pair which can be sent to the client. The same token pair can be json-decoded.

func (*Signer) Sign

func (s *Signer) Sign(claims interface{}, opts ...SignOption) ([]byte, error)

Sign generates a new token based on the given "claims" which is valid up to "s.MaxAge".

func (*Signer) WithEncryption

func (s *Signer) WithEncryption(key, additionalData []byte) *Signer

WithEncryption enables AES-GCM payload-only decryption.

type TokenExtractor

type TokenExtractor func(*context.Context) string

TokenExtractor is a function that takes a context as input and returns a token. An empty string should be returned if no token found without additional information.

func FromJSON

func FromJSON(jsonKey string) TokenExtractor

FromJSON is a token extractor. Reads a json request body and extracts the json based on the given field. The request content-type should contain the: application/json header value, otherwise this method will not try to read and consume the body.

type TokenPair

type TokenPair = jwt.TokenPair

TokenPair is just a helper structure which holds both access and refresh tokens.

type TokenValidator

type TokenValidator = jwt.TokenValidator

TokenValidator is the token validator interface alias.

type VerifiedToken

type VerifiedToken = jwt.VerifiedToken

VerifiedToken is the type alias for the verfieid token type, the result of the VerifyToken function.

func GetVerifiedToken

func GetVerifiedToken(ctx *context.Context) *VerifiedToken

GetVerifiedToken returns the verified token structure which holds information about the decoded token and its standard claims.

type Verifier

type Verifier struct {
	Alg Alg
	Key interface{}

	Decrypt func([]byte) ([]byte, error)

	Extractors []TokenExtractor
	Blocklist  Blocklist
	Validators []TokenValidator

	ErrorHandler func(ctx *context.Context, err error)
	// DisableContextUser disables the registration of the claims as context User.
	DisableContextUser bool
}

Verifier holds common options to verify an incoming token. Its Verify method can be used as a middleware to allow authorized clients to access an API.

It does not support JWE, JWK.

func NewVerifier

func NewVerifier(signatureAlg Alg, signatureKey interface{}, validators ...TokenValidator) *Verifier

NewVerifier accepts the algorithm for the token's signature among with its (public) key and optionally some token validators for all verify middlewares that may initialized under this Verifier. See its Verify method.

Usage:

verifier := NewVerifier(HS256, secret)

OR

verifier := NewVerifier(HS256, secret, Expected{Issuer: "my-app"})

claimsGetter := func() interface{} { return new(userClaims) }
middleware := verifier.Verify(claimsGetter)

OR

middleware := verifier.Verify(claimsGetter, Expected{Issuer: "my-app"})

Register the middleware, e.g.

app.Use(middleware)

Get the claims:

claims := jwt.Get(ctx).(*userClaims)
username := claims.Username

Get the context user:

username, err := ctx.User().GetUsername()

func (*Verifier) RequestToken

func (v *Verifier) RequestToken(ctx *context.Context) (token string)

RequestToken extracts the token from the request.

func (*Verifier) Verify

func (v *Verifier) Verify(claimsType func() interface{}, validators ...TokenValidator) context.Handler

Verify is the most important piece of code inside the Verifier. It accepts the "claimsType" function which should return a pointer to a custom structure which the token's decode claims valuee will be binded and validated to. Returns a common Iris handler which can be used as a middleware to protect an API from unauthorized client requests. After this, the route handlers can access the claims through the jwt.Get package-level function.

By default it extracts the token from Authorization: Bearer $token header and ?token URL Query parameter, to change that behavior modify its Extractors field.

By default a 401 status code with a generic message will be sent to the client on a token verification or claims validation failure, to change that behavior modify its ErrorHandler field or register OnErrorCode(401, errorHandler) and retrieve the error through Context.GetErr method.

If the "claimsType" is nil then only the jwt.GetVerifiedToken is available and the handler should unmarshal the payload to extract the claims by itself.

func (*Verifier) VerifyToken

func (v *Verifier) VerifyToken(token []byte, validators ...TokenValidator) (*VerifiedToken, error)

VerifyToken simply verifies the given "token" and validates its standard claims (such as expiration). Returns a structure which holds the token's information. See the Verify method instead.

func (*Verifier) WithDecryption

func (v *Verifier) WithDecryption(key, additionalData []byte) *Verifier

WithDecryption enables AES-GCM payload-only encryption.

func (*Verifier) WithDefaultBlocklist

func (v *Verifier) WithDefaultBlocklist() *Verifier

WithDefaultBlocklist attaches an in-memory blocklist storage to invalidate tokens through server-side. To invalidate a token simply call the Context.Logout method.

Directories

Path Synopsis
blocklist

Jump to

Keyboard shortcuts

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