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 ¶
- Constants
- Variables
- func DecodeSegment(seg string) ([]byte, error)
- func EncodeSegment(seg []byte) string
- func NewInvalidKeyTypeError(expected string, received interface{}) error
- func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error)
- func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error)
- func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)
- func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error)
- func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)
- func RegisterSigningMethod(alg string, f func() SigningMethod)
- type ClaimStrings
- type Claims
- type CodingContext
- type ErrorWrapper
- type FieldDescriptor
- type HashUnavailableError
- type InvalidAudienceError
- type InvalidClaimsError
- type InvalidIssuerError
- type InvalidKeyError
- type InvalidKeyTypeError
- type InvalidSignatureError
- type Keyfunc
- type MalformedTokenError
- type MapClaims
- type Parser
- type ParserOption
- func WithAudience(aud string) ParserOption
- func WithIssuer(iss string) ParserOption
- func WithJSONNumber() ParserOption
- func WithLeeway(d time.Duration) ParserOption
- func WithUnmarshaller(um TokenUnmarshaller) ParserOption
- func WithValidMethods(valid []string) ParserOption
- func WithoutAudienceValidation() ParserOption
- func WithoutClaimsValidation() ParserOption
- type SigningError
- type SigningMethod
- type SigningMethodECDSA
- type SigningMethodHMAC
- type SigningMethodRSA
- type SigningMethodRSAPSS
- type SigningOption
- type StandardClaims
- type Time
- type Token
- func New(method SigningMethod) *Token
- func NewWithClaims(method SigningMethod, claims Claims) *Token
- func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error)
- func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error)
- type TokenExpiredError
- type TokenMarshaller
- type TokenNotValidYetError
- type TokenUnmarshaller
- type UnverfiableTokenError
- type ValidationHelper
- func (h *ValidationHelper) After(t time.Time) bool
- func (h *ValidationHelper) Before(t time.Time) bool
- func (h *ValidationHelper) ValidateAudience(aud ClaimStrings) error
- func (h *ValidationHelper) ValidateAudienceAgainst(aud ClaimStrings, compare string) error
- func (h *ValidationHelper) ValidateExpiresAt(exp *Time) error
- func (h *ValidationHelper) ValidateIssuer(iss string) error
- func (h *ValidationHelper) ValidateIssuerAgainst(iss string, compare string) error
- func (h *ValidationHelper) ValidateNotBefore(nbf *Time) error
Examples ¶
Constants ¶
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
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 ¶
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
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
var DefaultValidationHelper = &ValidationHelper{}
DefaultValidationHelper is used by Claims.Valid if none is provided
var (
)Error constants
var NoneSignatureTypeDisallowedError error
NoneSignatureTypeDisallowedError is the error value returned when the none signing method is used without UnsafeAllowNoneSignatureType
var SigningMethodNone *signingMethodNone
SigningMethodNone implements the none signing method. This is required by the spec but you probably should never use it.
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 ¶
DecodeSegment is used internally for JWT specific base64url encoding with padding stripped
func EncodeSegment ¶
EncodeSegment is used internally for JWT specific base64url encoding with padding stripped
func NewInvalidKeyTypeError ¶
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 ¶
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 ¶
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) 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 {
}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 ¶
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 ¶
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 ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
func (c StandardClaims) 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 (*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 ¶
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 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 ¶
ParseTime is used for creating a Time value from various possible representations that can occur in serialization.
func (*Time) MarshalJSON ¶
MarshalJSON implements the json package's Marshaler interface
func (*Time) UnmarshalJSON ¶
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