package jwt

Import Path
	github.com/golang-jwt/jwt/v4 (on go.dev)

Dependency Relation
	imports 21 packages, and imported by 2 packages

Involved Source Files claims.go 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. ecdsa.go ecdsa_utils.go ed25519.go ed25519_utils.go errors.go hmac.go map_claims.go none.go parser.go parser_option.go rsa.go rsa_pss.go rsa_utils.go signing_method.go token.go types.go
Code Examples { mySigningKey := []byte("AllYourBase") type MyCustomClaims struct { Foo string `json:"foo"` jwt.RegisteredClaims } claims := MyCustomClaims{ "bar", jwt.RegisteredClaims{ 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"}, }, } claims = MyCustomClaims{ "bar", 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) } { mySigningKey := []byte("AllYourBase") 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) } { 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) } } { // 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) { fmt.Println("Timing is everything") } else { fmt.Println("Couldn't handle this token:", err) } }
Package-Level Type Names (total 17)
/* sort by: | */
Claims must just have a Valid method that determines if the token is invalid for any supported reason ( Claims) Valid() error MapClaims RegisteredClaims StandardClaims github.com/Nerzal/gocloak/v13.PermissionTicketRepresentation github.com/Nerzal/gocloak/v13/pkg/jwx.Claims *net/http.Cookie func NewWithClaims(method SigningMethod, claims Claims) *Token func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) func (*Parser).ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) func (*Parser).ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) func github.com/Nerzal/gocloak/v13.(*GoCloak).DecodeAccessTokenCustomClaims(ctx context.Context, accessToken, realm string, claims Claims) (*Token, error) func github.com/Nerzal/gocloak/v13/pkg/jwx.DecodeAccessTokenECDSACustomClaims(accessToken string, x, y, crv *string, customClaims Claims) (*Token, error) func github.com/Nerzal/gocloak/v13/pkg/jwx.DecodeAccessTokenRSACustomClaims(accessToken string, e, n *string, customClaims Claims) (*Token, error) func github.com/Nerzal/gocloak/v13/pkg/jwx.SignClaims(claims Claims, key interface{}, method SigningMethod) (string, error)
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. ( ClaimStrings) MarshalJSON() (b []byte, err error) (*ClaimStrings) UnmarshalJSON(data []byte) (err error) ClaimStrings : encoding/json.Marshaler *ClaimStrings : encoding/json.Unmarshaler
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. func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) func (*Parser).Parse(tokenString string, keyFunc Keyfunc) (*Token, error) func (*Parser).ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error)
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 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. VerifyAudience Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). If req is false, it will return true, if exp is unset. VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). If req is false, it will return true, if iat is unset. VerifyIssuer compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). If req is false, it will return true, if nbf is unset. MapClaims : Claims func github.com/Nerzal/gocloak/v13.(*GoCloak).DecodeAccessToken(ctx context.Context, accessToken, realm string) (*Token, *MapClaims, error)
NumericDate represents a JSON numeric date value, as referenced at https://datatracker.ietf.org/doc/html/rfc7519#section-2. Time time.Time Add returns the time t+d. AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010. AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31. After reports whether the time instant t is after u. AppendFormat is like Format but appends the textual representation to b and returns the extended buffer. Before reports whether the time instant t is before u. Clock returns the hour, minute, and second within the day specified by t. Compare compares the time instant t with u. If t is before u, it returns -1; if t is after u, it returns +1; if they're the same, it returns 0. Date returns the year, month, and day in which t occurs. Day returns the day of the month specified by t. Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead. Format returns a textual representation of the time value formatted according to the layout defined by the argument. See the documentation for the constant called Layout to see how to represent the layout format. The executable example for Time.Format demonstrates the working of the layout string in detail and is a good reference. GoString implements fmt.GoStringer and formats t to be printed in Go source code. GobDecode implements the gob.GobDecoder interface. GobEncode implements the gob.GobEncoder interface. Hour returns the hour within the day specified by t, in the range [0, 23]. ISOWeek returns the ISO 8601 year and week number in which t occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1. In returns a copy of t representing the same time instant, but with the copy's location information set to loc for display purposes. In panics if loc is nil. IsDST reports whether the time in the configured location is in Daylight Savings Time. IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC. Local returns t with the location set to local time. Location returns the time zone information associated with t. MarshalBinary implements the encoding.BinaryMarshaler interface. 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. MarshalText implements the encoding.TextMarshaler interface. The time is formatted in RFC 3339 format with sub-second precision. If the timestamp cannot be represented as valid RFC 3339 (e.g., the year is out of range), then an error is reported. Minute returns the minute offset within the hour specified by t, in the range [0, 59]. Month returns the month of the year specified by t. Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999]. Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged. Round operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Round(Hour) may return a time with a non-zero minute, depending on the time's Location. Second returns the second offset within the minute specified by t, in the range [0, 59]. String returns the time formatted using the format string "2006-01-02 15:04:05.999999999 -0700 MST" If the time has a monotonic clock reading, the returned string includes a final field "m=±<value>", where value is the monotonic clock reading formatted as a decimal number of seconds. The returned string is meant for debugging; for a stable serialized representation, use t.MarshalText, t.MarshalBinary, or t.Format with an explicit format string. Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d). Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged. Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Truncate(Hour) may return a time with a non-zero minute, depending on the time's Location. UTC returns t with the location set to UTC. Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t. Unix-like operating systems often record time as a 32-bit count of seconds, but since the method here returns a 64-bit value it is valid for billions of years into the past or future. UnixMicro returns t as a Unix time, the number of microseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in microseconds cannot be represented by an int64 (a date before year -290307 or after year 294246). The result does not depend on the location associated with t. UnixMilli returns t as a Unix time, the number of milliseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in milliseconds cannot be represented by an int64 (a date more than 292 million years before or after 1970). The result does not depend on the location associated with t. UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in nanoseconds cannot be represented by an int64 (a date before the year 1678 or after 2262). Note that this means the result of calling UnixNano on the zero Time is undefined. The result does not depend on the location associated with t. UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. 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. UnmarshalText implements the encoding.TextUnmarshaler interface. The time must be in the RFC 3339 format. Weekday returns the day of the week specified by t. Year returns the year in which t occurs. YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, and [1,366] in leap years. Zone computes the time zone in effect at time t, returning the abbreviated name of the zone (such as "CET") and its offset in seconds east of UTC. ZoneBounds returns the bounds of the time zone in effect at time t. The zone begins at start and the next zone begins at end. If the zone begins at the beginning of time, start will be returned as a zero Time. If the zone goes on forever, end will be returned as a zero Time. The Location of the returned times will be the same as t. NumericDate : github.com/ChrisTrenkamp/goxpath/tree.Result NumericDate : encoding.BinaryMarshaler *NumericDate : encoding.BinaryUnmarshaler NumericDate : encoding.TextMarshaler *NumericDate : encoding.TextUnmarshaler *NumericDate : encoding/gob.GobDecoder NumericDate : encoding/gob.GobEncoder NumericDate : encoding/json.Marshaler *NumericDate : encoding/json.Unmarshaler NumericDate : fmt.GoStringer NumericDate : fmt.Stringer func NewNumericDate(t time.Time) *NumericDate func github.com/Nerzal/gocloak/v13.(*GoCloak).LoginClientSignedJWT(ctx context.Context, clientID, realm string, key interface{}, signedMethod SigningMethod, expiresAt *NumericDate) (*gocloak.JWT, error)
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. 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. 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. Parse parses, validates, verifies the signature and returns the parsed token. keyFunc will receive the parsed token and should return the key for validating. 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. 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. func NewParser(options ...ParserOption) *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() ParserOption func WithoutClaimsValidation() ParserOption func WithValidMethods(methods []string) ParserOption func NewParser(options ...ParserOption) *Parser func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error)
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. the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 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. VerifyAudience compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset VerifyExpiresAt compares the exp claim against cmp (cmp < exp). If req is false, it will return true, if exp is unset. VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). If req is false, it will return true, if iat is unset. VerifyIssuer compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). If req is false, it will return true, if nbf is unset. RegisteredClaims : Claims
SigningMethod can be used add new methods for signing or verifying tokens. // returns the alg identifier for this method (example: 'HS256') // Returns encoded signature or error // Returns nil if signature is valid *SigningMethodECDSA *SigningMethodEd25519 *SigningMethodHMAC *SigningMethodRSA *SigningMethodRSAPSS func GetSigningMethod(alg string) (method SigningMethod) func New(method SigningMethod) *Token func NewWithClaims(method SigningMethod, claims Claims) *Token func github.com/Nerzal/gocloak/v13.(*GoCloak).LoginClientSignedJWT(ctx context.Context, clientID, realm string, key interface{}, signedMethod SigningMethod, expiresAt *NumericDate) (*gocloak.JWT, error) func github.com/Nerzal/gocloak/v13/pkg/jwx.SignClaims(claims Claims, key interface{}, method SigningMethod) (string, error)
SigningMethodECDSA implements the ECDSA family of signing methods. Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification CurveBits int Hash crypto.Hash KeySize int Name string (*SigningMethodECDSA) Alg() string Sign implements token signing for the SigningMethod. For this signing method, key must be an ecdsa.PrivateKey struct Verify implements token verification for the SigningMethod. For this verify method, key must be an ecdsa.PublicKey struct *SigningMethodECDSA : SigningMethod var SigningMethodES256 *SigningMethodECDSA var SigningMethodES384 *SigningMethodECDSA var SigningMethodES512 *SigningMethodECDSA
SigningMethodEd25519 implements the EdDSA family. Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification (*SigningMethodEd25519) Alg() string Sign implements token signing for the SigningMethod. For this signing method, key must be an ed25519.PrivateKey Verify implements token verification for the SigningMethod. For this verify method, key must be an ed25519.PublicKey *SigningMethodEd25519 : SigningMethod var SigningMethodEdDSA *SigningMethodEd25519
SigningMethodHMAC implements the HMAC-SHA family of signing methods. Expects key type of []byte for both signing and validation Hash crypto.Hash Name string (*SigningMethodHMAC) Alg() string Sign implements token signing for the SigningMethod. Key must be []byte Verify implements token verification for the SigningMethod. Returns nil if the signature is valid. *SigningMethodHMAC : SigningMethod var SigningMethodHS256 *SigningMethodHMAC var SigningMethodHS384 *SigningMethodHMAC var SigningMethodHS512 *SigningMethodHMAC
SigningMethodRSA implements the RSA family of signing methods. Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation Hash crypto.Hash Name string (*SigningMethodRSA) Alg() string Sign implements token signing for the SigningMethod For this signing method, must be an *rsa.PrivateKey structure. Verify implements token verification for the SigningMethod For this signing method, must be an *rsa.PublicKey structure. *SigningMethodRSA : SigningMethod var SigningMethodRS256 *SigningMethodRSA var SigningMethodRS384 *SigningMethodRSA var SigningMethodRS512 *SigningMethodRSA
SigningMethodRSAPSS implements the RSAPSS family of signing methods signing methods Options *rsa.PSSOptions SigningMethodRSA *SigningMethodRSA SigningMethodRSA.Hash crypto.Hash SigningMethodRSA.Name string 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. ( SigningMethodRSAPSS) Alg() string Sign implements token signing for the SigningMethod. For this signing method, key must be an rsa.PrivateKey struct Verify implements token verification for the SigningMethod. For this verify method, key must be an rsa.PublicKey struct *SigningMethodRSAPSS : SigningMethod var SigningMethodPS256 *SigningMethodRSAPSS var SigningMethodPS384 *SigningMethodRSAPSS var SigningMethodPS512 *SigningMethodRSAPSS
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. Audience string ExpiresAt int64 Id string IssuedAt int64 Issuer string NotBefore int64 Subject string 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. VerifyAudience compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset VerifyExpiresAt compares the exp claim against cmp (cmp < exp). If req is false, it will return true, if exp is unset. VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). If req is false, it will return true, if iat is unset. VerifyIssuer compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). If req is false, it will return true, if nbf is unset. StandardClaims : Claims
Token represents a JWT Token. Different fields will be used depending on whether you're creating or parsing/verifying a token. // The second segment of the token // The first segment of the token // The signing method used or to be used // The raw token. Populated when you Parse a token // The third segment of the token. Populated when you Parse a token // Is the token valid? Populated when you Parse/Verify a token SignedString creates and returns a complete, signed JWT. The token is signed using the SigningMethod specified in the token. 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. 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) func (*Parser).Parse(tokenString string, keyFunc Keyfunc) (*Token, error) func (*Parser).ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) func (*Parser).ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) func github.com/Nerzal/gocloak/v13.(*GoCloak).DecodeAccessToken(ctx context.Context, accessToken, realm string) (*Token, *MapClaims, error) func github.com/Nerzal/gocloak/v13.(*GoCloak).DecodeAccessTokenCustomClaims(ctx context.Context, accessToken, realm string, claims Claims) (*Token, error) func github.com/Nerzal/gocloak/v13/pkg/jwx.DecodeAccessTokenECDSACustomClaims(accessToken string, x, y, crv *string, customClaims Claims) (*Token, error) func github.com/Nerzal/gocloak/v13/pkg/jwx.DecodeAccessTokenRSACustomClaims(accessToken string, e, n *string, customClaims Claims) (*Token, error)
ValidationError represents an error from Parse if token is not valid // bitfield. see ValidationError... constants // stores the error returned by external dependencies, i.e.: KeyFunc Error is the implementation of the err interface. 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. Unwrap gives errors.Is and errors.As access to the inner error. ValidationError : error func NewValidationError(errorText string, errorFlags uint32) *ValidationError
Package-Level Functions (total 22)
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
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
GetAlgorithms returns a list of registered "alg" names
GetSigningMethod retrieves a signing method from an "alg" string
New creates a new Token with the specified signing method and an empty map of claims.
NewNumericDate constructs a new *NumericDate from a standard library time.Time struct. It will truncate the timestamp according to the precision specified in TimePrecision.
NewParser creates a new Parser with the specified options
NewValidationError is a helper for constructing a ValidationError with a string error message
NewWithClaims creates a new Token with the specified signing method and claims.
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/
ParseECPrivateKeyFromPEM parses a PEM encoded Elliptic Curve Private Key Structure
ParseECPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key
ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key
ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key
ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key
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.
ParseRSAPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key
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.
RegisterSigningMethod registers the "alg" name and a factory function for signing method. This is typically done during init() in the method's implementation
WithJSONNumber is an option to configure the underlying JSON parser with UseNumber
WithoutClaimsValidation is an option to disable claims validation. This option should only be used if you exactly know what you are doing.
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/.
Package-Level Variables (total 43)
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.
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.
Sadly this is missing from crypto/ecdsa compared to crypto/rsa
Error constants
Error constants
Error constants
Specific instances for HS256 and company
Error constants
Error constants
Error constants
Error constants
Error constants
Error constants
Error constants
Error constants
Error constants
Error constants
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.
Specific instance for EdDSA
Specific instances for EC256 and company
Specific instances for EC256 and company
Specific instances for EC256 and company
Specific instances for HS256 and company
Specific instances for HS256 and company
Specific instances for HS256 and company
SigningMethodNone implements the none signing method. This is required by the spec but you probably should never use it.
Specific instances for RS/PS and company.
Specific instances for RS/PS and company.
Specific instances for RS/PS and company.
Specific instances for RS256 and company
Specific instances for RS256 and company
Specific instances for RS256 and company
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.
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.
Package-Level Constants (total 11)
const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed"
Standard Claim validation errors
The errors that might occur when parsing and validating a token
The errors that might occur when parsing and validating a token
The errors that might occur when parsing and validating a token
The errors that might occur when parsing and validating a token
The errors that might occur when parsing and validating a token
The errors that might occur when parsing and validating a token
The errors that might occur when parsing and validating a token
The errors that might occur when parsing and validating a token
The errors that might occur when parsing and validating a token