jwt

package module
v4.5.0 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2022 License: MIT Imports: 21 Imported by: 6,710

README

jwt-go

build Go Reference

A go (or 'golang' for search engine friendliness) implementation of JSON Web Tokens.

Starting with v4.0.0 this project adds Go module support, but maintains backwards compatibility with older v3.x.y tags and upstream github.com/dgrijalva/jwt-go. See the MIGRATION_GUIDE.md for more information.

After the original author of the library suggested migrating the maintenance of jwt-go, a dedicated team of open source maintainers decided to clone the existing library into this repository. See dgrijalva/jwt-go#462 for a detailed discussion on this topic.

SECURITY NOTICE: Some older versions of Go have a security issue in the crypto/elliptic. Recommendation is to upgrade to at least 1.15 See issue dgrijalva/jwt-go#216 for more detail.

SECURITY NOTICE: It's important that you validate the alg presented is what you expect. This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided.

Supported Go versions

Our support of Go versions is aligned with Go's version release policy. So we will support a major version of Go until there are two newer major releases. We no longer support building jwt-go with unsupported Go versions, as these contain security vulnerabilities which will not be fixed.

What the heck is a JWT?

JWT.io has a great introduction to JSON Web Tokens.

In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for Bearer tokens in Oauth 2. A token is made of three parts, separated by .'s. The first two parts are JSON objects, that have been base64url encoded. The last part is the signature, encoded the same way.

The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used.

The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to RFC 7519 for information about reserved keys and the proper way to add your own.

What's in the box?

This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own.

Installation Guidelines

  1. To install the jwt package, you first need to have Go installed, then you can use the command below to add jwt-go as a dependency in your Go program.
go get -u github.com/golang-jwt/jwt/v4
  1. Import it in your code:
import "github.com/golang-jwt/jwt/v4"

Examples

See the project documentation for examples of usage:

Extensions

This library publishes all the necessary components for adding your own signing methods or key functions. Simply implement the SigningMethod interface and register a factory method using RegisterSigningMethod or provide a jwt.Keyfunc.

A common use case would be integrating with different 3rd party signature providers, like key management services from various cloud providers or Hardware Security Modules (HSMs) or to implement additional standards.

Extension Purpose Repo
GCP Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) https://github.com/someone1/gcp-jwt-go
AWS Integrates with AWS Key Management Service, KMS https://github.com/matelang/jwt-go-aws-kms
JWKS Provides support for JWKS (RFC 7517) as a jwt.Keyfunc https://github.com/MicahParks/keyfunc

Disclaimer: Unless otherwise specified, these integrations are maintained by third parties and should not be considered as a primary offer by any of the mentioned cloud providers

Compliance

This library was last reviewed to comply with RFC 7519 dated May 2015 with a few notable differences:

  • In order to protect against accidental use of Unsecured JWTs, tokens using alg=none will only be accepted if the constant jwt.UnsafeAllowNoneSignatureType is provided as the key.

Project Status & Versioning

This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason).

This project uses Semantic Versioning 2.0.0. Accepted pull requests will land on main. Periodically, versions will be tagged from main. You can find all the releases on the project releases page.

BREAKING CHANGES:* A full list of breaking changes is available in VERSION_HISTORY.md. See MIGRATION_GUIDE.md for more information on updating your code.

Usage Tips

Signing vs Encryption

A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data:

  • The author of the token was in the possession of the signing secret
  • The data has not been modified since it was signed

It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, JWE, that provides this functionality. The companion project https://github.com/golang-jwt/jwe aims at a (very) experimental implementation of the JWE standard.

Choosing a Signing Method

There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric.

Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any []byte can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation.

Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification.

Signing Methods and Key Types

Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones:

  • The HMAC signing method (HS256,HS384,HS512) expect []byte values for signing and validation
  • The RSA signing method (RS256,RS384,RS512) expect *rsa.PrivateKey for signing and *rsa.PublicKey for validation
  • The ECDSA signing method (ES256,ES384,ES512) expect *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for validation
  • The EdDSA signing method (Ed25519) expect ed25519.PrivateKey for signing and ed25519.PublicKey for validation
JWT and OAuth

It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication.

Without going too far down the rabbit hole, here's a description of the interaction of these technologies:

  • OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth.
  • OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that should only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token.
  • Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL.
Troubleshooting

This library uses descriptive error messages whenever possible. If you are not getting the expected result, have a look at the errors. The most common place people get stuck is providing the correct type of key to the parser. See the above section on signing methods and key types.

More

Documentation can be found on pkg.go.dev.

The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation.

golang-jwt incorporates a modified version of the JWT logo, which is distributed under the terms of the MIT License.

Documentation

Overview

Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html

See README.md for more info.

Example (GetTokenViaHTTP)
// See func authHandler for an example auth handler that produces a token
res, err := http.PostForm(fmt.Sprintf("http://localhost:%v/authenticate", serverPort), url.Values{
	"user": {"test"},
	"pass": {"known"},
})
if err != nil {
	fatal(err)
}

if res.StatusCode != 200 {
	fmt.Println("Unexpected status code", res.StatusCode)
}

// Read the token out of the response body
buf := new(bytes.Buffer)
io.Copy(buf, res.Body)
res.Body.Close()
tokenString := strings.TrimSpace(buf.String())

// Parse the token
token, err := jwt.ParseWithClaims(tokenString, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) {
	// since we only use the one private key to sign the tokens,
	// we also only use its public counter part to verify
	return verifyKey, nil
})
fatal(err)

claims := token.Claims.(*CustomClaimsExample)
fmt.Println(claims.CustomerInfo.Name)
Output:

test
Example (UseTokenViaHTTP)
// Make a sample token
// In a real world situation, this token will have been acquired from
// some other API call (see Example_getTokenViaHTTP)
token, err := createToken("foo")
fatal(err)

// Make request.  See func restrictedHandler for example request processor
req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%v/restricted", serverPort), nil)
fatal(err)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token))
res, err := http.DefaultClient.Do(req)
fatal(err)

// Read the response body
buf := new(bytes.Buffer)
io.Copy(buf, res.Body)
res.Body.Close()
fmt.Println(buf.String())
Output:

Welcome, foo

Index

Examples

Constants

View Source
const (
	ValidationErrorMalformed        uint32 = 1 << iota // Token is malformed
	ValidationErrorUnverifiable                        // Token could not be verified because of signing problems
	ValidationErrorSignatureInvalid                    // Signature validation failed

	// Standard Claim validation errors
	ValidationErrorAudience      // AUD validation failed
	ValidationErrorExpired       // EXP validation failed
	ValidationErrorIssuedAt      // IAT validation failed
	ValidationErrorIssuer        // ISS validation failed
	ValidationErrorNotValidYet   // NBF validation failed
	ValidationErrorId            // JTI validation failed
	ValidationErrorClaimsInvalid // Generic claims validation error
)

The errors that might occur when parsing and validating a token

View Source
const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed"

Variables

View Source
var (
	ErrNotECPublicKey  = errors.New("key is not a valid ECDSA public key")
	ErrNotECPrivateKey = errors.New("key is not a valid ECDSA private key")
)
View Source
var (
	ErrNotEdPrivateKey = errors.New("key is not a valid Ed25519 private key")
	ErrNotEdPublicKey  = errors.New("key is not a valid Ed25519 public key")
)
View Source
var (
	ErrInvalidKey      = errors.New("key is invalid")
	ErrInvalidKeyType  = errors.New("key is of invalid type")
	ErrHashUnavailable = errors.New("the requested hash function is unavailable")

	ErrTokenMalformed        = errors.New("token is malformed")
	ErrTokenUnverifiable     = errors.New("token is unverifiable")
	ErrTokenSignatureInvalid = errors.New("token signature is invalid")

	ErrTokenInvalidAudience  = errors.New("token has invalid audience")
	ErrTokenExpired          = errors.New("token is expired")
	ErrTokenUsedBeforeIssued = errors.New("token used before issued")
	ErrTokenInvalidIssuer    = errors.New("token has invalid issuer")
	ErrTokenNotValidYet      = errors.New("token is not valid yet")
	ErrTokenInvalidId        = errors.New("token has invalid id")
	ErrTokenInvalidClaims    = errors.New("token has invalid claims")
)

Error constants

View Source
var (
	ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key")
	ErrNotRSAPrivateKey    = errors.New("key is not a valid RSA private key")
	ErrNotRSAPublicKey     = errors.New("key is not a valid RSA public key")
)
View Source
var DecodePaddingAllowed bool

DecodePaddingAllowed will switch the codec used for decoding JWTs respectively. Note that the JWS RFC7515 states that the tokens will utilize a Base64url encoding with no padding. Unfortunately, some implementations of JWT are producing non-standard tokens, and thus require support for decoding. Note that this is a global variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. To use the non-recommended decoding, set this boolean to `true` prior to using this package.

View Source
var DecodeStrict bool

DecodeStrict will switch the codec used for decoding JWTs into strict mode. In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5. Note that this is a global variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. To use strict decoding, set this boolean to `true` prior to using this package.

View Source
var (
	// Sadly this is missing from crypto/ecdsa compared to crypto/rsa
	ErrECDSAVerification = errors.New("crypto/ecdsa: verification error")
)
View Source
var (
	ErrEd25519Verification = errors.New("ed25519: verification error")
)
View Source
var MarshalSingleStringAsArray = true

MarshalSingleStringAsArray modifies the behaviour of the ClaimStrings type, especially its MarshalJSON function.

If it is set to true (the default), it will always serialize the type as an array of strings, even if it just contains one element, defaulting to the behaviour of the underlying []string. If it is set to false, it will serialize to a single string, if it contains one element. Otherwise, it will serialize to an array of strings.

View Source
var NoneSignatureTypeDisallowedError error
View Source
var SigningMethodNone *signingMethodNone

SigningMethodNone implements the none signing method. This is required by the spec but you probably should never use it.

View Source
var TimeFunc = time.Now

TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.

View Source
var TimePrecision = time.Second

TimePrecision sets the precision of times and dates within this library. This has an influence on the precision of times when comparing expiry or other related time fields. Furthermore, it is also the precision of times when serializing.

For backwards compatibility the default precision is set to seconds, so that no fractional timestamps are generated.

Functions

func DecodeSegment deprecated

func DecodeSegment(seg string) ([]byte, error)

DecodeSegment decodes a JWT specific base64url encoding with padding stripped

Deprecated: In a future release, we will demote this function to a non-exported function, since it should only be used internally

func EncodeSegment deprecated

func EncodeSegment(seg []byte) string

EncodeSegment encodes a JWT specific base64url encoding with padding stripped

Deprecated: In a future release, we will demote this function to a non-exported function, since it should only be used internally

func GetAlgorithms added in v4.2.0

func GetAlgorithms() (algs []string)

GetAlgorithms returns a list of registered "alg" names

func ParseECPrivateKeyFromPEM

func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error)

ParseECPrivateKeyFromPEM parses a PEM encoded Elliptic Curve Private Key Structure

func ParseECPublicKeyFromPEM

func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error)

ParseECPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key

func ParseEdPrivateKeyFromPEM

func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error)

ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key

func ParseEdPublicKeyFromPEM

func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error)

ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key

func ParseRSAPrivateKeyFromPEM

func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)

ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key

func ParseRSAPrivateKeyFromPEMWithPassword deprecated

func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error)

ParseRSAPrivateKeyFromPEMWithPassword parses a PEM encoded PKCS1 or PKCS8 private key protected with password

Deprecated: This function is deprecated and should not be used anymore. It uses the deprecated x509.DecryptPEMBlock function, which was deprecated since RFC 1423 is regarded insecure by design. Unfortunately, there is no alternative in the Go standard library for now. See https://github.com/golang/go/issues/8860.

func ParseRSAPublicKeyFromPEM

func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)

ParseRSAPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key

func RegisterSigningMethod

func RegisterSigningMethod(alg string, f func() SigningMethod)

RegisterSigningMethod registers the "alg" name and a factory function for signing method. This is typically done during init() in the method's implementation

Types

type ClaimStrings added in v4.1.0

type ClaimStrings []string

ClaimStrings is basically just a slice of strings, but it can be either serialized from a string array or just a string. This type is necessary, since the "aud" claim can either be a single string or an array.

func (ClaimStrings) MarshalJSON added in v4.1.0

func (s ClaimStrings) MarshalJSON() (b []byte, err error)

func (*ClaimStrings) UnmarshalJSON added in v4.1.0

func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error)

type Claims

type Claims interface {
	Valid() error
}

Claims must just have a Valid method that determines if the token is invalid for any supported reason

type Keyfunc

type Keyfunc func(*Token) (interface{}, error)

Keyfunc will be used by the Parse methods as a callback function to supply the key for verification. The function receives the parsed, but unverified Token. This allows you to use properties in the Header of the token (such as `kid`) to identify which key to use.

type MapClaims

type MapClaims map[string]interface{}

MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. This is the default claims type if you don't supply one

func (MapClaims) Valid

func (m MapClaims) Valid() error

Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.

func (MapClaims) VerifyAudience

func (m MapClaims) VerifyAudience(cmp string, req bool) bool

VerifyAudience Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset

func (MapClaims) VerifyExpiresAt

func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool

VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). If req is false, it will return true, if exp is unset.

func (MapClaims) VerifyIssuedAt

func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool

VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). If req is false, it will return true, if iat is unset.

func (MapClaims) VerifyIssuer

func (m MapClaims) VerifyIssuer(cmp string, req bool) bool

VerifyIssuer compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset

func (MapClaims) VerifyNotBefore

func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool

VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). If req is false, it will return true, if nbf is unset.

type NumericDate added in v4.1.0

type NumericDate struct {
	time.Time
}

NumericDate represents a JSON numeric date value, as referenced at https://datatracker.ietf.org/doc/html/rfc7519#section-2.

func NewNumericDate added in v4.1.0

func NewNumericDate(t time.Time) *NumericDate

NewNumericDate constructs a new *NumericDate from a standard library time.Time struct. It will truncate the timestamp according to the precision specified in TimePrecision.

func (NumericDate) MarshalJSON added in v4.1.0

func (date NumericDate) MarshalJSON() (b []byte, err error)

MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epoch represented in NumericDate to a byte array, using the precision specified in TimePrecision.

func (*NumericDate) UnmarshalJSON added in v4.1.0

func (date *NumericDate) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON is an implementation of the json.RawMessage interface and deserializses a NumericDate from a JSON representation, i.e. a json.Number. This number represents an UNIX epoch with either integer or non-integer seconds.

type Parser

type Parser struct {
	// If populated, only these methods will be considered valid.
	//
	// Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead.
	ValidMethods []string

	// Use JSON Number format in JSON decoder.
	//
	// Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead.
	UseJSONNumber bool

	// Skip claims validation during token parsing.
	//
	// Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead.
	SkipClaimsValidation bool
}

func NewParser added in v4.2.0

func NewParser(options ...ParserOption) *Parser

NewParser creates a new Parser with the specified options

func (*Parser) Parse

func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error)

Parse parses, validates, verifies the signature and returns the parsed token. keyFunc will receive the parsed token and should return the key for validating.

func (*Parser) ParseUnverified

func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error)

ParseUnverified parses the token but doesn't validate the signature.

WARNING: Don't use this method unless you know what you're doing.

It's only ever useful in cases where you know the signature is valid (because it has been checked previously in the stack) and you want to extract values from it.

func (*Parser) ParseWithClaims

func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error)

ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims interface. This provides default values which can be overridden and allows a caller to use their own type, rather than the default MapClaims implementation of Claims.

Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the proper memory for it before passing in the overall claims, otherwise you might run into a panic.

type ParserOption added in v4.2.0

type ParserOption func(*Parser)

ParserOption is used to implement functional-style options that modify the behavior of the parser. To add new options, just create a function (ideally beginning with With or Without) that returns an anonymous function that takes a *Parser type as input and manipulates its configuration accordingly.

func WithJSONNumber added in v4.2.0

func WithJSONNumber() ParserOption

WithJSONNumber is an option to configure the underlying JSON parser with UseNumber

func WithValidMethods added in v4.2.0

func WithValidMethods(methods []string) ParserOption

WithValidMethods is an option to supply algorithm methods that the parser will check. Only those methods will be considered valid. It is heavily encouraged to use this option in order to prevent attacks such as https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/.

func WithoutClaimsValidation added in v4.2.0

func WithoutClaimsValidation() ParserOption

WithoutClaimsValidation is an option to disable claims validation. This option should only be used if you exactly know what you are doing.

type RegisteredClaims added in v4.1.0

type RegisteredClaims struct {
	// the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1
	Issuer string `json:"iss,omitempty"`

	// the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2
	Subject string `json:"sub,omitempty"`

	// the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3
	Audience ClaimStrings `json:"aud,omitempty"`

	// the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4
	ExpiresAt *NumericDate `json:"exp,omitempty"`

	// the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5
	NotBefore *NumericDate `json:"nbf,omitempty"`

	// the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6
	IssuedAt *NumericDate `json:"iat,omitempty"`

	// the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7
	ID string `json:"jti,omitempty"`
}

RegisteredClaims are a structured version of the JWT Claims Set, restricted to Registered Claim Names, as referenced at https://datatracker.ietf.org/doc/html/rfc7519#section-4.1

This type can be used on its own, but then additional private and public claims embedded in the JWT will not be parsed. The typical usecase therefore is to embedded this in a user-defined claim type.

See examples for how to use this with your own claim types.

func (RegisteredClaims) Valid added in v4.1.0

func (c RegisteredClaims) Valid() error

Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.

func (*RegisteredClaims) VerifyAudience added in v4.1.0

func (c *RegisteredClaims) VerifyAudience(cmp string, req bool) bool

VerifyAudience compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*RegisteredClaims) VerifyExpiresAt added in v4.1.0

func (c *RegisteredClaims) VerifyExpiresAt(cmp time.Time, req bool) bool

VerifyExpiresAt compares the exp claim against cmp (cmp < exp). If req is false, it will return true, if exp is unset.

func (*RegisteredClaims) VerifyIssuedAt added in v4.1.0

func (c *RegisteredClaims) VerifyIssuedAt(cmp time.Time, req bool) bool

VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). If req is false, it will return true, if iat is unset.

func (*RegisteredClaims) VerifyIssuer added in v4.2.0

func (c *RegisteredClaims) VerifyIssuer(cmp string, req bool) bool

VerifyIssuer compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*RegisteredClaims) VerifyNotBefore added in v4.1.0

func (c *RegisteredClaims) VerifyNotBefore(cmp time.Time, req bool) bool

VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). If req is false, it will return true, if nbf is unset.

type SigningMethod

type SigningMethod interface {
	Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid
	Sign(signingString string, key interface{}) (string, error)    // Returns encoded signature or error
	Alg() string                                                   // returns the alg identifier for this method (example: 'HS256')
}

SigningMethod can be used add new methods for signing or verifying tokens.

func GetSigningMethod

func GetSigningMethod(alg string) (method SigningMethod)

GetSigningMethod retrieves a signing method from an "alg" string

type SigningMethodECDSA

type SigningMethodECDSA struct {
	Name      string
	Hash      crypto.Hash
	KeySize   int
	CurveBits int
}

SigningMethodECDSA implements the ECDSA family of signing methods. Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification

var (
	SigningMethodES256 *SigningMethodECDSA
	SigningMethodES384 *SigningMethodECDSA
	SigningMethodES512 *SigningMethodECDSA
)

Specific instances for EC256 and company

func (*SigningMethodECDSA) Alg

func (m *SigningMethodECDSA) Alg() string

func (*SigningMethodECDSA) Sign

func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error)

Sign implements token signing for the SigningMethod. For this signing method, key must be an ecdsa.PrivateKey struct

func (*SigningMethodECDSA) Verify

func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error

Verify implements token verification for the SigningMethod. For this verify method, key must be an ecdsa.PublicKey struct

type SigningMethodEd25519

type SigningMethodEd25519 struct{}

SigningMethodEd25519 implements the EdDSA family. Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification

var (
	SigningMethodEdDSA *SigningMethodEd25519
)

Specific instance for EdDSA

func (*SigningMethodEd25519) Alg

func (m *SigningMethodEd25519) Alg() string

func (*SigningMethodEd25519) Sign

func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) (string, error)

Sign implements token signing for the SigningMethod. For this signing method, key must be an ed25519.PrivateKey

func (*SigningMethodEd25519) Verify

func (m *SigningMethodEd25519) Verify(signingString, signature string, key interface{}) error

Verify implements token verification for the SigningMethod. For this verify method, key must be an ed25519.PublicKey

type SigningMethodHMAC

type SigningMethodHMAC struct {
	Name string
	Hash crypto.Hash
}

SigningMethodHMAC implements the HMAC-SHA family of signing methods. Expects key type of []byte for both signing and validation

var (
	SigningMethodHS256  *SigningMethodHMAC
	SigningMethodHS384  *SigningMethodHMAC
	SigningMethodHS512  *SigningMethodHMAC
	ErrSignatureInvalid = errors.New("signature is invalid")
)

Specific instances for HS256 and company

func (*SigningMethodHMAC) Alg

func (m *SigningMethodHMAC) Alg() string

func (*SigningMethodHMAC) Sign

func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error)

Sign implements token signing for the SigningMethod. Key must be []byte

func (*SigningMethodHMAC) Verify

func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error

Verify implements token verification for the SigningMethod. Returns nil if the signature is valid.

type SigningMethodRSA

type SigningMethodRSA struct {
	Name string
	Hash crypto.Hash
}

SigningMethodRSA implements the RSA family of signing methods. Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation

var (
	SigningMethodRS256 *SigningMethodRSA
	SigningMethodRS384 *SigningMethodRSA
	SigningMethodRS512 *SigningMethodRSA
)

Specific instances for RS256 and company

func (*SigningMethodRSA) Alg

func (m *SigningMethodRSA) Alg() string

func (*SigningMethodRSA) Sign

func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error)

Sign implements token signing for the SigningMethod For this signing method, must be an *rsa.PrivateKey structure.

func (*SigningMethodRSA) Verify

func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error

Verify implements token verification for the SigningMethod For this signing method, must be an *rsa.PublicKey structure.

type SigningMethodRSAPSS

type SigningMethodRSAPSS struct {
	*SigningMethodRSA
	Options *rsa.PSSOptions
	// VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS.
	// Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow
	// https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously.
	// See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details.
	VerifyOptions *rsa.PSSOptions
}

SigningMethodRSAPSS implements the RSAPSS family of signing methods signing methods

var (
	SigningMethodPS256 *SigningMethodRSAPSS
	SigningMethodPS384 *SigningMethodRSAPSS
	SigningMethodPS512 *SigningMethodRSAPSS
)

Specific instances for RS/PS and company.

func (*SigningMethodRSAPSS) Sign

func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error)

Sign implements token signing for the SigningMethod. For this signing method, key must be an rsa.PrivateKey struct

func (*SigningMethodRSAPSS) Verify

func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error

Verify implements token verification for the SigningMethod. For this verify method, key must be an rsa.PublicKey struct

type StandardClaims deprecated

type StandardClaims struct {
	Audience  string `json:"aud,omitempty"`
	ExpiresAt int64  `json:"exp,omitempty"`
	Id        string `json:"jti,omitempty"`
	IssuedAt  int64  `json:"iat,omitempty"`
	Issuer    string `json:"iss,omitempty"`
	NotBefore int64  `json:"nbf,omitempty"`
	Subject   string `json:"sub,omitempty"`
}

StandardClaims are a structured version of the JWT Claims Set, as referenced at https://datatracker.ietf.org/doc/html/rfc7519#section-4. They do not follow the specification exactly, since they were based on an earlier draft of the specification and not updated. The main difference is that they only support integer-based date fields and singular audiences. This might lead to incompatibilities with other JWT implementations. The use of this is discouraged, instead the newer RegisteredClaims struct should be used.

Deprecated: Use RegisteredClaims instead for a forward-compatible way to access registered claims in a struct.

func (StandardClaims) Valid

func (c StandardClaims) Valid() error

Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.

func (*StandardClaims) VerifyAudience

func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool

VerifyAudience compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*StandardClaims) VerifyExpiresAt

func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool

VerifyExpiresAt compares the exp claim against cmp (cmp < exp). If req is false, it will return true, if exp is unset.

func (*StandardClaims) VerifyIssuedAt

func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool

VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). If req is false, it will return true, if iat is unset.

func (*StandardClaims) VerifyIssuer

func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool

VerifyIssuer compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*StandardClaims) VerifyNotBefore

func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool

VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). If req is false, it will return true, if nbf is unset.

type Token

type Token struct {
	Raw       string                 // The raw token.  Populated when you Parse a token
	Method    SigningMethod          // The signing method used or to be used
	Header    map[string]interface{} // The first segment of the token
	Claims    Claims                 // The second segment of the token
	Signature string                 // The third segment of the token.  Populated when you Parse a token
	Valid     bool                   // Is the token valid?  Populated when you Parse/Verify a token
}

Token represents a JWT Token. Different fields will be used depending on whether you're creating or parsing/verifying a token.

func New

func New(method SigningMethod) *Token

New creates a new Token with the specified signing method and an empty map of claims.

Example (Hmac)

Example creating, signing, and encoding a JWT token using the HMAC signing method

// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
	"foo": "bar",
	"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
})

// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString(hmacSampleSecret)

fmt.Println(tokenString, err)
Output:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU <nil>

func NewWithClaims

func NewWithClaims(method SigningMethod, claims Claims) *Token

NewWithClaims creates a new Token with the specified signing method and claims.

Example (CustomClaimsType)

Example creating a token using a custom claims type. The RegisteredClaims is embedded in the custom type to allow for easy encoding, parsing and validation of registered claims.

mySigningKey := []byte("AllYourBase")

type MyCustomClaims struct {
	Foo string `json:"foo"`
	jwt.RegisteredClaims
}

// Create the claims
claims := MyCustomClaims{
	"bar",
	jwt.RegisteredClaims{
		// A usual scenario is to set the expiration time relative to the current time
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
		IssuedAt:  jwt.NewNumericDate(time.Now()),
		NotBefore: jwt.NewNumericDate(time.Now()),
		Issuer:    "test",
		Subject:   "somebody",
		ID:        "1",
		Audience:  []string{"somebody_else"},
	},
}

// Create claims while leaving out some of the optional fields
claims = MyCustomClaims{
	"bar",
	jwt.RegisteredClaims{
		// Also fixed dates can be used for the NumericDate
		ExpiresAt: jwt.NewNumericDate(time.Unix(1516239022, 0)),
		Issuer:    "test",
	},
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(mySigningKey)
fmt.Printf("%v %v", ss, err)
Output:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.xVuY2FZ_MRXMIEgVQ7J-TFtaucVFRXUzHm9LmV41goM <nil>
Example (RegisteredClaims)

Example (atypical) using the RegisteredClaims type by itself to parse a token. The RegisteredClaims type is designed to be embedded into your custom types to provide standard validation features. You can use it alone, but there's no way to retrieve other fields after parsing. See the CustomClaimsType example for intended usage.

mySigningKey := []byte("AllYourBase")

// Create the Claims
claims := &jwt.RegisteredClaims{
	ExpiresAt: jwt.NewNumericDate(time.Unix(1516239022, 0)),
	Issuer:    "test",
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(mySigningKey)
fmt.Printf("%v %v", ss, err)
Output:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.0XN_1Tpp9FszFOonIBpwha0c_SfnNI22DhTnjMshPg8 <nil>

func Parse

func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error)

Parse parses, validates, verifies the signature and returns the parsed token. keyFunc will receive the parsed token and should return the cryptographic key for verifying the signature. The caller is strongly encouraged to set the WithValidMethods option to validate the 'alg' claim in the token matches the expected algorithm. For more details about the importance of validating the 'alg' claim, see https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/

Example (ErrorChecking)

An example of parsing the error types using bitfield checks

// Token from another example.  This token is expired
var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
	return []byte("AllYourBase"), nil
})

if token.Valid {
	fmt.Println("You look nice today")
} else if errors.Is(err, jwt.ErrTokenMalformed) {
	fmt.Println("That's not even a token")
} else if errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet) {
	// Token is either expired or not active yet
	fmt.Println("Timing is everything")
} else {
	fmt.Println("Couldn't handle this token:", err)
}
Output:

Timing is everything
Example (Hmac)

Example parsing and validating a token using the HMAC signing method

// sample token string taken from the New example
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU"

// Parse takes the token string and a function for looking up the key. The latter is especially
// useful if you use multiple keys for your application.  The standard is to use 'kid' in the
// head of the token to identify which key to use, but the parsed token (head and claims) is provided
// to the callback, providing flexibility.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
	// Don't forget to validate the alg is what you expect:
	if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
		return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
	}

	// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
	return hmacSampleSecret, nil
})

if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
	fmt.Println(claims["foo"], claims["nbf"])
} else {
	fmt.Println(err)
}
Output:

bar 1.4444784e+09

func ParseWithClaims

func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error)

ParseWithClaims is a shortcut for NewParser().ParseWithClaims().

Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the proper memory for it before passing in the overall claims, otherwise you might run into a panic.

Example (CustomClaimsType)

Example creating a token using a custom claims type. The StandardClaim is embedded in the custom type to allow for easy encoding, parsing and validation of standard claims.

tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA"

type MyCustomClaims struct {
	Foo string `json:"foo"`
	jwt.RegisteredClaims
}

token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
	return []byte("AllYourBase"), nil
})

if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
	fmt.Printf("%v %v", claims.Foo, claims.RegisteredClaims.Issuer)
} else {
	fmt.Println(err)
}
Output:

bar test

func (*Token) SignedString

func (t *Token) SignedString(key interface{}) (string, error)

SignedString creates and returns a complete, signed JWT. The token is signed using the SigningMethod specified in the token.

func (*Token) SigningString

func (t *Token) SigningString() (string, error)

SigningString generates the signing string. This is the most expensive part of the whole deal. Unless you need this for something special, just go straight for the SignedString.

type ValidationError

type ValidationError struct {
	Inner  error  // stores the error returned by external dependencies, i.e.: KeyFunc
	Errors uint32 // bitfield.  see ValidationError... constants
	// contains filtered or unexported fields
}

ValidationError represents an error from Parse if token is not valid

func NewValidationError

func NewValidationError(errorText string, errorFlags uint32) *ValidationError

NewValidationError is a helper for constructing a ValidationError with a string error message

func (ValidationError) Error

func (e ValidationError) Error() string

Error is the implementation of the err interface.

func (*ValidationError) Is added in v4.3.0

func (e *ValidationError) Is(err error) bool

Is checks if this ValidationError is of the supplied error. We are first checking for the exact error message by comparing the inner error message. If that fails, we compare using the error flags. This way we can use custom error messages (mainly for backwards compatability) and still leverage errors.Is using the global error variables.

func (*ValidationError) Unwrap added in v4.2.0

func (e *ValidationError) Unwrap() error

Unwrap gives errors.Is and errors.As access to the inner error.

Directories

Path Synopsis
cmd
jwt
A useful example app.
A useful example app.
Utility package for extracting JWT tokens from HTTP requests.
Utility package for extracting JWT tokens from HTTP requests.

Jump to

Keyboard shortcuts

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