jwt

package module
v4.0.0-preview1 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2020 License: MIT Imports: 19 Imported by: 344

README

jwt-go

Build Status GoDoc

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

NEW VERSION: Version 4 of this library is now available. This is the first non-backward-compatible version in a long time. There are a few changes that all users will notice, such as the new types introduced in members of StandardClaims. More changes are additive or only impact more advanced use. See VERSION_HISTORY.md for a list of changes as well as TODO MIGRATION_GUIDE.md for help updating your code.

SECURITY NOTICE: Some older versions of Go have a security issue in the cryotp/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #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.

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 the RFC 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.

Examples

See the project documentation for examples of usage:

Extensions

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

Here's an example of an extension that integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS): https://github.com/someone1/gcp-jwt-go

Compliance

This library was last reviewed to comply with RTF 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 master. Periodically, versions will be tagged from master. You can find all the releases on the project releases page.

As of version 4, this project is compatible with go modules. You should use that to ensure you have no unpleasant surprises when updating.

BREAKING CHANGES:*

  • Version 4.0.0 includes a lot of changes from the 3.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature 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. JWE is currently outside the scope of this library.

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
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.

More

Documentation can be found on godoc.org.

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.

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 TimePrecision = time.Microsecond

TimePrecision determines how precisely time is measured by this library. When serializing and deserialzing tokens, time values are automatically truncated to this precision. See the time package's Truncate method for more detail

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

UnsafeAllowNoneSignatureType must be returned from Keyfunc in order for the none signing method to be allowed. This is intended to make is possible to use this signing method, but not by accident

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")
)

Errors returned by EC signing methods

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

Errors returned by RSA Signing Method and helpers

View Source
var DefaultValidationHelper = &ValidationHelper{}

DefaultValidationHelper is used by Claims.Valid if none is provided

View Source
var (
	ErrHashUnavailable = new(HashUnavailableError)
)

Error constants

View Source
var NoneSignatureTypeDisallowedError error

NoneSignatureTypeDisallowedError is the error value returned when the none signing method is used without UnsafeAllowNoneSignatureType

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.

Functions

func DecodeSegment

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

DecodeSegment is used internally for JWT specific base64url encoding with padding stripped

func EncodeSegment

func EncodeSegment(seg []byte) string

EncodeSegment is used internally for JWT specific base64url encoding with padding stripped

func NewInvalidKeyTypeError

func NewInvalidKeyTypeError(expected string, received interface{}) error

NewInvalidKeyTypeError creates an InvalidKeyTypeError, automatically capturing the type of received

func ParseECPrivateKeyFromPEM

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

ParseECPrivateKeyFromPEM is a helper function for parsing a PEM encoded Elliptic Curve Private Key Structure

func ParseECPublicKeyFromPEM

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

ParseECPublicKeyFromPEM is a helper function for parsing a PEM encoded PKCS1 or PKCS8 public key

func ParseRSAPrivateKeyFromPEM

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

ParseRSAPrivateKeyFromPEM is a helper method for parsing PEM encoded PKCS1 or PKCS8 private key

func ParseRSAPrivateKeyFromPEMWithPassword

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

ParseRSAPrivateKeyFromPEMWithPassword is a helper method for parsing PEM encoded PKCS1 or PKCS8 private key, encrypted with a password

func ParseRSAPublicKeyFromPEM

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

ParseRSAPublicKeyFromPEM is a helper method for parsing a PEM encoded PKCS1 or PKCS8 public key

func RegisterSigningMethod

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

RegisterSigningMethod stores the "alg" name and a factory function pair used internally for looking up a signing method based on "alg". This is typically done during init() in the method's implementation

Types

type ClaimStrings

type ClaimStrings []string

ClaimStrings is used for parsing claim properties that can be either a string or array of strings

func ParseClaimStrings

func ParseClaimStrings(value interface{}) (ClaimStrings, error)

ParseClaimStrings is used to produce a ClaimStrings value from the various forms it may present during encoding/decodeing

func (*ClaimStrings) UnmarshalJSON

func (c *ClaimStrings) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json package's Unmarshaler interface

type Claims

type Claims interface {
	// A nil validation helper should use the default helper
	Valid(*ValidationHelper) error
}

Claims is the interface used to hold the claims values of a token For a type to be a Claims object, it must have a Valid method that determines if the token is invalid for any supported reason Claims are parsed and encoded using the standard library's encoding/json package. Claims are passed directly to that.

type CodingContext

type CodingContext struct {
	FieldDescriptor                        // Which field are we encoding/decoding?
	Header          map[string]interface{} // The token Header, if available
}

CodingContext provides context to TokenMarshaller and TokenUnmarshaller

type ErrorWrapper

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

ErrorWrapper provides a simple, concrete helper for implementing nestable errors

func (ErrorWrapper) Unwrap

func (w ErrorWrapper) Unwrap() error

Unwrap implements xerrors.Wrapper

func (ErrorWrapper) Wrap

func (w ErrorWrapper) Wrap(err error)

Wrap stores the provided error value and returns it when Unwrap is called

type FieldDescriptor

type FieldDescriptor uint8

FieldDescriptor describes which field is being processed. Used by CodingContext This is to enable the marshaller to treat the head and body differently

const (
	HeaderFieldDescriptor FieldDescriptor = 0
	ClaimsFieldDescriptor FieldDescriptor = 1
)

Constants describe which field is being processed by custom Marshaller

type HashUnavailableError

type HashUnavailableError struct {
	ErrorWrapper
}

HashUnavailableError measn the request hash function isn't available See: https://godoc.org/crypto#Hash.Available

func (*HashUnavailableError) Error

func (e *HashUnavailableError) Error() string

type InvalidAudienceError

type InvalidAudienceError struct {
	Message string
	ErrorWrapper
}

InvalidAudienceError means the token failed the audience check per the spec, if an 'aud' claim is present, the value must be verified See: WithAudience and WithoutAudienceValidation

func (*InvalidAudienceError) Error

func (e *InvalidAudienceError) Error() string

type InvalidClaimsError

type InvalidClaimsError struct {
	Message string
	ErrorWrapper
}

InvalidClaimsError is a catchall type for claims errors that don't have their own type

func (*InvalidClaimsError) Error

func (e *InvalidClaimsError) Error() string

type InvalidIssuerError

type InvalidIssuerError struct {
	Message string
	ErrorWrapper
}

InvalidIssuerError means the token failed issuer validation Issuer validation is only run, by default, if the WithIssuer option is provided

func (*InvalidIssuerError) Error

func (e *InvalidIssuerError) Error() string

type InvalidKeyError

type InvalidKeyError struct {
	Message string
	ErrorWrapper
}

InvalidKeyError is returned if the key is unusable for some reason other than type

func (*InvalidKeyError) Error

func (e *InvalidKeyError) Error() string

type InvalidKeyTypeError

type InvalidKeyTypeError struct {
	Expected, Received string // String descriptions of expected and received types
	ErrorWrapper
}

InvalidKeyTypeError is returned if the key is unusable because it is of an incompatible type

func (*InvalidKeyTypeError) Error

func (e *InvalidKeyTypeError) Error() string

type InvalidSignatureError

type InvalidSignatureError struct {
	Message string
	ErrorWrapper
}

InvalidSignatureError means the signature on the token is invalid

func (*InvalidSignatureError) Error

func (e *InvalidSignatureError) Error() string

type Keyfunc

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

Keyfunc is the type passed to Parse methods 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.

func KnownKeyfunc

func KnownKeyfunc(signingMethod SigningMethod, key interface{}) Keyfunc

KnownKeyfunc is a helper for generating a Keyfunc from a known signing method and key. If your implementation only supports a single signing method and key, this is for you.

type MalformedTokenError

type MalformedTokenError struct {
	Message string
	ErrorWrapper
}

MalformedTokenError means the token failed to parse or exhibits some other non-standard property that prevents it being processed by this library

func (*MalformedTokenError) Error

func (e *MalformedTokenError) Error() string

type MapClaims

type MapClaims map[string]interface{}

MapClaims is the 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) LoadTimeValue

func (m MapClaims) LoadTimeValue(key string) (*Time, error)

LoadTimeValue extracts a *Time value from a key in m

func (MapClaims) Valid

func (m MapClaims) Valid(h *ValidationHelper) error

Valid validates standard claims using ValidationHelper Validates time based claims "exp, nbf" (see: WithLeeway) Validates "aud" if present in claims. (see: WithAudience, WithoutAudienceValidation) Validates "iss" if option is provided (see: WithIssuer)

func (MapClaims) VerifyAudience

func (m MapClaims) VerifyAudience(h *ValidationHelper, cmp string) error

VerifyAudience compares the aud claim against cmp.

func (MapClaims) VerifyIssuer

func (m MapClaims) VerifyIssuer(h *ValidationHelper, cmp string) error

VerifyIssuer compares the iss claim against cmp.

type Parser

type Parser struct {
	*ValidationHelper
	// contains filtered or unexported fields
}

Parser is the type used to parse and validate a JWT token from string

func NewParser

func NewParser(options ...ParserOption) *Parser

NewParser returns a new Parser with the specified options

func (*Parser) Parse

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

Parse will parse, validate, and return a token. keyFunc will receive the parsed token and should return the key for validating. If everything is kosher, err will be nil

func (*Parser) ParseUnverified

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

ParseUnverified is used to inspect a token without validating it WARNING: Don't use this method unless you know what you're doing

This method parses the token but doesn't validate the signature. 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. Or for debuggery.

func (*Parser) ParseWithClaims

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

ParseWithClaims is just like parse, but with the claims type specified

type ParserOption

type ParserOption func(*Parser)

ParserOption implements functional options for parser behavior see: https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis

func WithAudience

func WithAudience(aud string) ParserOption

WithAudience returns the ParserOption for specifying an expected aud member value

func WithIssuer

func WithIssuer(iss string) ParserOption

WithIssuer returns the ParserOption that specifies a value to compare against the iss claim

func WithJSONNumber

func WithJSONNumber() ParserOption

WithJSONNumber returns the ParserOption for using json.Number instead of float64 when parsing numeric values. Used most commonly with MapClaims, but it can be useful in some cases with structured claims types

func WithLeeway

func WithLeeway(d time.Duration) ParserOption

WithLeeway returns the ParserOption for specifying the leeway window.

func WithUnmarshaller

func WithUnmarshaller(um TokenUnmarshaller) ParserOption

WithUnmarshaller returns the ParserOption that replaces the specified decoder

func WithValidMethods

func WithValidMethods(valid []string) ParserOption

WithValidMethods returns the ParserOption for specifying valid signing methods

func WithoutAudienceValidation

func WithoutAudienceValidation() ParserOption

WithoutAudienceValidation returns the ParserOption that specifies audience check should be skipped

func WithoutClaimsValidation

func WithoutClaimsValidation() ParserOption

WithoutClaimsValidation returns the ParserOption for disabling claims validation This does not disable signature validation. Use this if you want intend to implement claims validation via other means

type SigningError

type SigningError struct {
	Message string
	ErrorWrapper
}

SigningError is a catchall type for signing errors

func (*SigningError) Error

func (e *SigningError) Error() string

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 is the interface used for signing and verifying tokens

func GetSigningMethod

func GetSigningMethod(alg string) (method SigningMethod)

GetSigningMethod returns the signing method registered by RegisterSigningMethod This is used by the library internally during parsing and validation.

type SigningMethodECDSA

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

SigningMethodECDSA implements the ECDSA family of signing methods 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

Alg implements SigningMethod

func (*SigningMethodECDSA) Sign

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

Sign implements the Sign method from 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 the Verify method from SigningMethod For this verify method, key must be an ecdsa.PublicKey struct

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

Alg implements SigningMethod

func (*SigningMethodHMAC) Sign

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

Sign implements the Sign method from SigningMethod Key must be []byte

func (*SigningMethodHMAC) Verify

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

Verify the signature of HSXXX tokens. 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 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

Alg implements the Alg method from SigningMethod

func (*SigningMethodRSA) Sign

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

Sign implements the Sign method from 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 the Verify method from SigningMethod For this signing method, must be an *rsa.PublicKey structure.

type SigningMethodRSAPSS

type SigningMethodRSAPSS struct {
	*SigningMethodRSA
	Options *rsa.PSSOptions
}

SigningMethodRSAPSS implements the RSAPSS family of 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 the Sign method from 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 the Verify method from SigningMethod For this verify method, key must be an rsa.PublicKey struct

type SigningOption

type SigningOption func(*signingOptions)

SigningOption can be passed to signing related methods on Token to customize behavior

func WithMarshaller

func WithMarshaller(m TokenMarshaller) SigningOption

WithMarshaller returns a SigningOption that will tell the signing code to use your custom Marshaller

type StandardClaims

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

StandardClaims is a structured version of Claims Section, as referenced at https://tools.ietf.org/html/rfc7519#section-4.1 See examples for how to use this with your own claim types

func (StandardClaims) Valid

Valid validates standard claims using ValidationHelper Validates time based claims "exp, nbf" (see: WithLeeway) Validates "aud" if present in claims. (see: WithAudience, WithoutAudienceValidation) Validates "iss" if option is provided (see: WithIssuer)

func (*StandardClaims) VerifyAudience

func (c *StandardClaims) VerifyAudience(h *ValidationHelper, cmp string) error

VerifyAudience compares the aud claim against cmp.

func (*StandardClaims) VerifyIssuer

func (c *StandardClaims) VerifyIssuer(h *ValidationHelper, cmp string) error

VerifyIssuer compares the iss claim against cmp.

type Time

type Time struct {
	time.Time
}

Time is how this library represents time values. It's mostly a wrapper for the standard library's time.Time, but adds specialized JSON decoding behavior to interop with the way time is represented by JWT. Also makes it possible to represent nil values.

func At

func At(at time.Time) *Time

At makes a Time value from a standard library time.Time value

func NewTime

func NewTime(t float64) *Time

NewTime creates a new Time value from a float64, following the JWT spec.

func Now

func Now() *Time

Now returns a new Time value using the current time. You can override Now by changing the value of TimeFunc

func ParseTime

func ParseTime(value interface{}) (*Time, error)

ParseTime is used for creating a Time value from various possible representations that can occur in serialization.

func (*Time) MarshalJSON

func (t *Time) MarshalJSON() ([]byte, error)

MarshalJSON implements the json package's Marshaler interface

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json package's Unmarshaler interface

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 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. Takes a signing method. Uses the default claims type, MapClaims.

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 creats a new token with a specified signing method and claims type

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.

mySigningKey := []byte("AllYourBase")

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

// Create the Claims
claims := MyCustomClaims{
	"bar",
	jwt.StandardClaims{
		ExpiresAt: jwt.NewTime(15000),
		Issuer:    "test",
	},
}

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

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c <nil>
Example (StandardClaims)

Example (atypical) using the StandardClaims type by itself to parse a token. The StandardClaims 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.StandardClaims{
	ExpiresAt: jwt.NewTime(15000),
	Issuer:    "test",
}

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

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 <nil>

func Parse

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

Parse then validate, and return a token. keyFunc will receive the parsed token and should return the key for validating. If everything is kosher, err will be nil Claims type will be the default, MapClaims

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
})

var uErr *jwt.UnverfiableTokenError
var expErr *jwt.TokenExpiredError
var nbfErr *jwt.TokenNotValidYetError

// Use xerrors.Is to see what kind of error(s) occurred
if token.Valid {
	fmt.Println("You look nice today")
} else if xerrors.As(err, &uErr) {
	fmt.Println("That's not even a token")
} else if xerrors.As(err, &expErr) {
	fmt.Println("Timing is everything")
} else if xerrors.As(err, &nbfErr) {
	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 Parse, but with a specified Claims type

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.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"

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

// sample token is expired.  override time so it parses as valid
test.At(time.Unix(0, 0), func() {
	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.StandardClaims.ExpiresAt.Unix())
	} else {
		fmt.Println(err)
	}
})
Output:

bar 15000

func (*Token) SignedString

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

SignedString returns the complete, signed token

func (*Token) SigningString

func (t *Token) SigningString(opts ...SigningOption) (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 TokenExpiredError

type TokenExpiredError struct {
	At           time.Time     // The time at which the exp was evaluated. Includes leeway.
	ExpiredBy    time.Duration // How long the token had been expired at time of evaluation
	ErrorWrapper               // Value for unwrapping
}

TokenExpiredError allows the caller to know the delta between now and the expired time and the unvalidated claims. A client system may have a bug that doesn't refresh a token in time, or there may be clock skew so this information can help you understand.

func (*TokenExpiredError) Error

func (e *TokenExpiredError) Error() string

type TokenMarshaller

type TokenMarshaller func(ctx CodingContext, v interface{}) ([]byte, error)

TokenMarshaller is the interface you must implement to provide custom JSON marshalling behavior. It is the same as json.Marshal with the addition of the FieldDescriptor. The field value will let your marshaller know which field is being processed. This is to facilitate things like compression, where you wouldn't want to compress the head.

type TokenNotValidYetError

type TokenNotValidYetError struct {
	At           time.Time     // The time at which the exp was evaluated. Includes leeway.
	EarlyBy      time.Duration // How long the token had been expired at time of evaluation
	ErrorWrapper               // Value for unwrapping
}

TokenNotValidYetError means the token failed the 'nbf' check. It's possible this token will become valid once the 'nbf' time is reached. If you are encountering this unexpectedly, you may want to provide a bit of Leeway to account for clock skew. See WithLeeway

func (*TokenNotValidYetError) Error

func (e *TokenNotValidYetError) Error() string

type TokenUnmarshaller

type TokenUnmarshaller func(ctx CodingContext, data []byte, v interface{}) error

TokenUnmarshaller is the function signature required to supply custom JSON decoding logic. It is the same as json.Marshal with the addition of the FieldDescriptor. The field value will let your marshaller know which field is being processed. This is to facilitate things like compression, where you wouldn't want to compress the head.

type UnverfiableTokenError

type UnverfiableTokenError struct {
	Message string
	ErrorWrapper
}

UnverfiableTokenError means there's something wrong with the signature that prevents this library from verifying it.

func (*UnverfiableTokenError) Error

func (e *UnverfiableTokenError) Error() string

type ValidationHelper

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

ValidationHelper is built by the parser and passed to Claims.Value to carry parse/validation options This standalone type exists to allow implementations to do whatever custom behavior is required while still being able to call upon the standard behavior as necessary.

func NewValidationHelper

func NewValidationHelper(options ...ParserOption) *ValidationHelper

NewValidationHelper creates a validation helper from a list of parser options Not all parser options will impact validation If you already have a custom parser, you can use its ValidationHelper value instead of creating a new one

func (*ValidationHelper) After

func (h *ValidationHelper) After(t time.Time) bool

After returns true if Now is after t Takes leeway into account

func (*ValidationHelper) Before

func (h *ValidationHelper) Before(t time.Time) bool

Before returns true if Now is before t Takes leeway into account

func (*ValidationHelper) ValidateAudience

func (h *ValidationHelper) ValidateAudience(aud ClaimStrings) error

ValidateAudience verifies that aud contains the audience value provided by the WithAudience option. Per the spec (https://tools.ietf.org/html/rfc7519#section-4.1.3), if the aud claim is present,

func (*ValidationHelper) ValidateAudienceAgainst

func (h *ValidationHelper) ValidateAudienceAgainst(aud ClaimStrings, compare string) error

ValidateAudienceAgainst checks that the compare value is included in the aud list It is used by ValidateAudience, but exposed as a helper for other implementations

func (*ValidationHelper) ValidateExpiresAt

func (h *ValidationHelper) ValidateExpiresAt(exp *Time) error

ValidateExpiresAt returns an error if the expiration time is invalid Takes leeway into account

func (*ValidationHelper) ValidateIssuer

func (h *ValidationHelper) ValidateIssuer(iss string) error

ValidateIssuer checks the claim value against the value provided by WithIssuer

func (*ValidationHelper) ValidateIssuerAgainst

func (h *ValidationHelper) ValidateIssuerAgainst(iss string, compare string) error

ValidateIssuerAgainst checks the claim value against the value provided, ignoring the WithIssuer value

func (*ValidationHelper) ValidateNotBefore

func (h *ValidationHelper) ValidateNotBefore(nbf *Time) error

ValidateNotBefore returns an error if the nbf time has not been reached Takes leeway into account

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