Documentation
¶
Overview ¶
Package jwt signs and verifies JSON Web Tokens.
It has no single Handler entry point: NewSigner(alg, key, maxAge) issues tokens and NewVerifier(alg, key, validators...) validates them, and it is the Verifier's `Verify` method that returns the Handler. The two halves are separate objects because most applications sign in one place and verify in another.
Index ¶
- Variables
- func FromHeader(ctx *context.Context) string
- func FromQuery(ctx *context.Context) string
- func Get[T any](ctx *context.Context) (T, bool)
- type Alg
- type Blocklist
- type Claims
- type ClaimsContextValidator
- type ClaimsValidator
- type Expected
- type SignOption
- type Signer
- type TokenExtractor
- type TokenPair
- type TokenValidator
- type VerifiedToken
- type Verifier
- func (v *Verifier) RequestToken(ctx *context.Context) (token string)
- func (v *Verifier) Verify(claimsType func() any, validators ...TokenValidator) context.Handler
- func (v *Verifier) VerifyToken(token []byte, validators ...TokenValidator) (*VerifiedToken, error)
- func (v *Verifier) WithDecryption(key, additionalData []byte) *Verifier
- func (v *Verifier) WithDefaultBlocklist() *Verifier
- func (v *Verifier) WithQueryToken() *Verifier
Constants ¶
This section is empty.
Variables ¶
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.
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.
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.
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.
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 } } )
var ( Verify = jwt.Verify VerifyEncryptedToken = jwt.VerifyEncrypted Sign = jwt.Sign SignEncrypted = jwt.SignEncrypted )
Shortcuts for Signing and Verifying.
Functions ¶
func FromHeader ¶
FromHeader is a token extractor. It reads the token from the Authorization request header of form: Authorization: "Bearer {token}".
func FromQuery ¶
FromQuery is a token extractor. It reads the token from the "token" url query parameter.
Security note: tokens placed in the URL query string tend to leak into access logs, proxy logs, browser history and Referer headers. As of v14 FromQuery is NOT one of the default extractors; opt in explicitly with Verifier.WithQueryToken only when header-based extraction is not possible.
func Get ¶
Get returns the claims decoded by a verifier, as type T. It reports false when the request carries no claims or when they are not a T; it never panics.
The stored value is what the claims constructor passed to Verify returned, usually a pointer, so T is that pointer type:
claims, ok := jwt.Get[*UserClaims](ctx)
Types ¶
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 `jwt.NewBlocklist` and `jwt.NewBlocklistContext` functions of the github.com/kataras/jwt package return a memory storage of tokens; use the `Verifier.WithDefaultBlocklist` method to attach one.
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 ClaimsContextValidator ¶
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 ¶
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 any
// 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 ¶
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 any, refreshClaims any, 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 any, opts ...SignOption) ([]byte, error)
Sign generates a new token based on the given "claims" which is valid up to "s.MaxAge".
func (*Signer) WithEncryption ¶
WithEncryption enables AES-GCM payload-only encryption of the signed token.
type TokenExtractor ¶
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 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 any
// HeaderValidator is optional. When it is nil the header check is the byte
// exact one of github.com/kataras/jwt: the header may hold the "alg" of the
// Verifier and "typ": "JWT" and nothing else, so a token with one more header
// field, such as the "kid" that Auth0 and most identity providers add, is
// rejected with ErrTokenAlg.
//
// Set it to check the header yourself. The function receives the name of Alg
// (empty when Alg is nil) and the decoded header, and it must always compare
// the "alg" of the header with the algorithm it expects. It may also return
// the algorithm, the key and a payload decrypter for that token: a returned
// key replaces Key, a returned algorithm is used only when Alg is nil and a
// returned decrypter runs before Decrypt. The ValidateHeader method of a
// github.com/kataras/jwt Keys or KeySet is such a function and selects them
// by "kid":
//
// verifier := NewVerifier(nil, nil)
// verifier.HeaderValidator = keySet.ValidateHeader
HeaderValidator jwt.HeaderValidator
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. A key set (JWK) is supported through its HeaderValidator field.
func NewVerifier ¶
func NewVerifier(signatureAlg Alg, signatureKey any, 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() any { 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, ok := jwt.Get[*userClaims](ctx)
if !ok {
return // the request went through no verifier.
}
ctx.Writef("hello %s", claims.Username)
Get the context user:
username, err := ctx.User().GetUsername()
func (*Verifier) RequestToken ¶
RequestToken extracts the token from the request.
func (*Verifier) Verify ¶
func (v *Verifier) Verify(claimsType func() any, 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 the Authorization: Bearer $token header only. Query-parameter (?token=) extraction is opt-in through the Verifier.WithQueryToken method, or by modifying 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 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.
The token's header is checked by the HeaderValidator field when that is set.
func (*Verifier) WithDecryption ¶
WithDecryption enables AES-GCM payload-only decryption of the incoming token.
func (*Verifier) WithDefaultBlocklist ¶
WithDefaultBlocklist attaches an in-memory blocklist storage to invalidate tokens through server-side. To invalidate a token simply call the Context.Logout method.
func (*Verifier) WithQueryToken ¶
WithQueryToken adds the query-parameter (?token=) extractor to the verifier.
As of v14 the default extractors read the Authorization header only, because tokens placed in the URL query string tend to leak into access logs, proxy logs, browser history and Referer headers. Opt back in only when you must (e.g. browser downloads that cannot set an Authorization header):
verifier := jwt.NewVerifier(jwt.HS256, key).WithQueryToken()