ClaimsValidator is an interface that can be implemented by custom claims who
wish to execute any additional claims validation based on
application-specific logic. The Validate function is then executed in
addition to the regular claims validation and any error returned is appended
to the final validation result.
type MyCustomClaims struct {
Foo string `json:"foo"`
jwt.RegisteredClaims
}
func (m MyCustomClaims) Validate() error {
if m.Foo != "bar" {
return errors.New("must be foobar")
}
return nil
}( ClaimsValidator) GetAudience() (ClaimStrings, error)( ClaimsValidator) GetExpirationTime() (*NumericDate, error)( ClaimsValidator) GetIssuedAt() (*NumericDate, error)( ClaimsValidator) GetIssuer() (string, error)( ClaimsValidator) GetNotBefore() (*NumericDate, error)( ClaimsValidator) GetSubject() (string, error)( ClaimsValidator) Validate() error
ClaimsValidator : Claims
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.
The returned interface{} may be a single key or a VerificationKeySet containing
multiple keys.
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 GetAudience implements the Claims interface. GetExpirationTime implements the Claims interface. GetIssuedAt implements the Claims interface. GetIssuer implements the Claims interface. GetNotBefore implements the Claims interface. GetSubject implements the Claims interface. parseClaimsString tries to parse a key in the map claims type as a
[ClaimsStrings] type, which can either be a string or an array of string. parseNumericDate tries to parse a key in the map claims type as a number
date. This will succeed, if the underlying type is either a [float64] or a
[json.Number]. Otherwise, nil will be returned. parseString tries to parse a key in the map claims type as a [string] type.
If the key does not exist, an empty string is returned. If the key has the
wrong type, an error is returned.
MapClaims : Claims
NumericDate represents a JSON numeric date value, as referenced at
https://datatracker.ietf.org/doc/html/rfc7519#section-2.Timetime.TimeTime.extint64 loc specifies the Location that should be used to
determine the minute, hour, month, day, and year
that correspond to this Time.
The nil location means UTC.
All UTC times are represented with loc==nil, never loc==&utcLoc. wall and ext encode the wall time seconds, wall time nanoseconds,
and optional monotonic clock reading in nanoseconds.
From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
a 33-bit seconds field, and a 30-bit wall time nanoseconds field.
The nanoseconds field is in the range [0, 999999999].
If the hasMonotonic bit is 0, then the 33-bit field must be zero
and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext.
If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit
unsigned wall seconds since Jan 1 year 1885, and ext holds a
signed 64-bit monotonic clock reading, nanoseconds since process start. 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.
Note that dates are fundamentally coupled to timezones, and calendrical
periods like days don't have fixed durations. AddDate uses the Location of
the Time value to determine these durations. That means that the same
AddDate arguments can produce a different shift in absolute time depending on
the base Time value and its Location. For example, AddDate(0, 0, 1) applied
to 12:00 on March 27 always returns 12:00 on March 28. At some locations and
in some years this is a 24 hour shift. In others it's a 23 hour shift due to
daylight savings time transitions.
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 [Time.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
deserializes 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. abs returns the time t as an absolute time, adjusted by the zone offset.
It is called when computing a presentation property like Month or Hour. addSec adds d seconds to the time.( NumericDate) appendFormat(b []byte, layout string) []byte( NumericDate) appendFormatRFC3339(b []byte, nanos bool) []byte( NumericDate) appendStrictRFC3339(b []byte) ([]byte, error) date computes the year, day of year, and when full=true,
the month and day in which t occurs. locabs is a combination of the Zone and abs methods,
extracting both return values from a single zone lookup. mono returns t's monotonic clock reading.
It returns 0 for a missing reading.
This function is used only for testing,
so it's OK that technically 0 is a valid
monotonic clock reading as well. nsec returns the time's nanoseconds. sec returns the time's seconds since Jan 1 year 1. setLoc sets the location associated with the time. setMono sets the monotonic clock reading in t.
If t cannot hold a monotonic clock reading,
because its wall time is too large,
setMono is a no-op. stripMono strips the monotonic clock reading in t. unixSec returns the time's seconds since Jan 1 1970 (Unix time).
NumericDate : encoding.BinaryMarshaler
*NumericDate : encoding.BinaryUnmarshaler
NumericDate : encoding.TextMarshaler
*NumericDate : encoding.TextUnmarshaler
NumericDate : encoding/json.Marshaler
*NumericDate : encoding/json.Unmarshaler
NumericDate : fmt.GoStringer
NumericDate : fmt.Stringer
NumericDate : context.stringer
*NumericDate : crypto/hmac.marshalable
NumericDate : runtime.stringer
func NewNumericDate(t time.Time) *NumericDate
func Claims.GetExpirationTime() (*NumericDate, error)
func Claims.GetIssuedAt() (*NumericDate, error)
func Claims.GetNotBefore() (*NumericDate, error)
func ClaimsValidator.GetExpirationTime() (*NumericDate, error)
func ClaimsValidator.GetIssuedAt() (*NumericDate, error)
func ClaimsValidator.GetNotBefore() (*NumericDate, error)
func MapClaims.GetExpirationTime() (*NumericDate, error)
func MapClaims.GetIssuedAt() (*NumericDate, error)
func MapClaims.GetNotBefore() (*NumericDate, error)
func RegisteredClaims.GetExpirationTime() (*NumericDate, error)
func RegisteredClaims.GetIssuedAt() (*NumericDate, error)
func RegisteredClaims.GetNotBefore() (*NumericDate, error)
func newNumericDateFromSeconds(f float64) *NumericDate
func MapClaims.parseNumericDate(key string) (*NumericDate, error)
decodePaddingAllowedbooldecodeStrictbool Skip claims validation during token parsing. Use JSON Number format in JSON decoder. If populated, only these methods will be considered valid.validator*Validator DecodeSegment decodes a JWT specific base64url encoding. This function will
take into account whether the [Parser] is configured with additional options,
such as [WithStrictDecoding] or [WithPaddingAllowed]. 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 (since it has already
been or will be checked elsewhere 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
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 use-case
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 GetAudience implements the Claims interface. GetExpirationTime implements the Claims interface. GetIssuedAt implements the Claims interface. GetIssuer implements the Claims interface. GetNotBefore implements the Claims interface. GetSubject implements the Claims interface.
RegisteredClaims : Claims
SigningMethodECDSA implements the ECDSA family of signing methods.
Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verificationCurveBitsintHashcrypto.HashKeySizeintNamestring(*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 validationHashcrypto.HashNamestring(*SigningMethodHMAC) Alg() string Sign implements token signing for the SigningMethod. Key must be []byte.
Note it is not advised to provide a []byte which was converted from a 'human
readable' string using a subset of ASCII characters. To maximize entropy, you
should ideally be providing a []byte key which was produced from a
cryptographically random source, e.g. crypto/rand. Additional information
about this, and why we intentionally are not supporting string as a key can
be found on our usage guide https://golang-jwt.github.io/jwt/usage/signing_methods/. Verify implements token verification for the SigningMethod. Returns nil if
the signature is valid. Key must be []byte.
Note it is not advised to provide a []byte which was converted from a 'human
readable' string using a subset of ASCII characters. To maximize entropy, you
should ideally be providing a []byte key which was produced from a
cryptographically random source, e.g. crypto/rand. Additional information
about this, and why we intentionally are not supporting string as a key can
be found on our usage guide
https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types.
*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 validationHashcrypto.HashNamestring(*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 methodsOptions*rsa.PSSOptionsSigningMethodRSA*SigningMethodRSASigningMethodRSA.Hashcrypto.HashSigningMethodRSA.Namestring 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
Token represents a JWT Token. Different fields will be used depending on
whether you're creating or parsing/verifying a token. // Claims is the second segment of the token in decoded form // Header is the first segment of the token in decoded form // Method is the signing method used or to be used // Raw contains the raw token. Populated when you [Parse] a token // Signature is the third segment of the token in decoded form. Populated when you Parse a token // Valid specifies if the token is valid. Populated when you Parse/Verify a token EncodeSegment encodes a JWT specific base64url encoding with padding
stripped. In the future, this function might take into account a
[TokenOption]. Therefore, this function exists as a method of [Token], rather
than a global function. SignedString creates and returns a complete, signed JWT. The token is signed
using the SigningMethod specified in the token. Please refer to
https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types
for an overview of the different signing methods and their respective key
types. 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, opts ...TokenOption) *Token
func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *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)
TokenOption is a reserved type, which provides some forward compatibility,
if we ever want to introduce token creation-related options.
func New(method SigningMethod, opts ...TokenOption) *Token
func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token
Validator is the core of the new Validation API. It is automatically used by
a [Parser] during parsing and can be modified with various parser options.
The [NewValidator] function should be used to create an instance of this
struct. expectedAud contains the audience this token expects. Supplying an empty
string will disable aud checking. expectedIss contains the issuer this token expects. Supplying an empty
string will disable iss checking. expectedSub contains the subject this token expects. Supplying an empty
string will disable sub checking. leeway is an optional leeway that can be provided to account for clock skew. requireExp specifies whether the exp claim is required timeFunc is used to supply the current time that is needed for
validation. If unspecified, this defaults to time.Now. verifyIat specifies whether the iat (Issued At) claim will be verified.
According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this
only specifies the age of the token, but no validation check is
necessary. However, if wanted, it can be checked if the iat is
unrealistic, i.e., in the future. Validate validates the given claims. It will also perform any custom
validation if claims implements the [ClaimsValidator] interface.
Note: It will NOT perform any *signature verification* on the token that
contains the claims and expects that the [Claim] was already successfully
verified. verifyAudience compares the aud claim against cmp.
If aud is not set or an empty list, it will succeed if the claim is not required,
otherwise ErrTokenRequiredClaimMissing will be returned.
Additionally, if any error occurs while retrieving the claim, e.g., when its
the wrong type, an ErrTokenUnverifiable error will be returned. verifyExpiresAt compares the exp claim in claims against cmp. This function
will succeed if cmp < exp. Additional leeway is taken into account.
If exp is not set, it will succeed if the claim is not required,
otherwise ErrTokenRequiredClaimMissing will be returned.
Additionally, if any error occurs while retrieving the claim, e.g., when its
the wrong type, an ErrTokenUnverifiable error will be returned. verifyIssuedAt compares the iat claim in claims against cmp. This function
will succeed if cmp >= iat. Additional leeway is taken into account.
If iat is not set, it will succeed if the claim is not required,
otherwise ErrTokenRequiredClaimMissing will be returned.
Additionally, if any error occurs while retrieving the claim, e.g., when its
the wrong type, an ErrTokenUnverifiable error will be returned. verifyIssuer compares the iss claim in claims against cmp.
If iss is not set, it will succeed if the claim is not required,
otherwise ErrTokenRequiredClaimMissing will be returned.
Additionally, if any error occurs while retrieving the claim, e.g., when its
the wrong type, an ErrTokenUnverifiable error will be returned. verifyNotBefore compares the nbf claim in claims against cmp. This function
will return true if cmp >= nbf. Additional leeway is taken into account.
If nbf is not set, it will succeed if the claim is not required,
otherwise ErrTokenRequiredClaimMissing will be returned.
Additionally, if any error occurs while retrieving the claim, e.g., when its
the wrong type, an ErrTokenUnverifiable error will be returned. verifySubject compares the sub claim against cmp.
If sub is not set, it will succeed if the claim is not required,
otherwise ErrTokenRequiredClaimMissing will be returned.
Additionally, if any error occurs while retrieving the claim, e.g., when its
the wrong type, an ErrTokenUnverifiable error will be returned.
func NewValidator(opts ...ParserOption) *Validator
VerificationKey represents a public or secret key for verifying a token's signature.
VerificationKeySet is a set of public or secret keys. It is used by the parser to verify a token.Keys[]VerificationKey
joinedError is an error type that works similar to what [errors.Join]
produces, with the exception that it has a nice error string; mainly its
error messages are concatenated using a comma, rather than a newline.errs[]error( joinedError) Error() string Unwrap implements the multiple error unwrapping for this error type, which is
possible in Go 1.20.
joinedError : error
(*signingMethodNone) Alg() string Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key
*signingMethodNone : SigningMethod
var SigningMethodNone *signingMethodNone
Package-Level Functions (total 41, in which 29 are exported)
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. Additional options can be specified, but are currently unused.
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
NewValidator can be used to create a stand-alone validator with the supplied
options. This validator can then be used to validate already parsed claims.
Note: Under normal circumstances, explicitly creating a validator is not
needed and can potentially be dangerous; instead functions of the [Parser]
class should be used.
The [Validator] is only checking the *validity* of the claims, such as its
expiration time, but it does NOT perform *signature verification* of the
token.
NewWithClaims creates a new [Token] with the specified signing method and
claims. Additional options can be specified, but are currently unused.
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 certificate or a PEM encoded PKCS1 or PKIX 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
WithAudience configures the validator to require the specified audience in
the `aud` claim. Validation will fail if the audience is not listed in the
token or the `aud` claim is missing.
NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is
application-specific. Since this validation API is helping developers in
writing secure application, we decided to REQUIRE the existence of the claim,
if an audience is expected.
WithExpirationRequired returns the ParserOption to make exp claim required.
By default exp claim is optional.
WithIssuedAt returns the ParserOption to enable verification
of issued-at.
WithIssuer configures the validator to require the specified issuer in the
`iss` claim. Validation will fail if a different issuer is specified in the
token or the `iss` claim is missing.
NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is
application-specific. Since this validation API is helping developers in
writing secure application, we decided to REQUIRE the existence of the claim,
if an issuer is expected.
WithJSONNumber is an option to configure the underlying JSON parser with
UseNumber.
WithLeeway returns the ParserOption for specifying the leeway window.
WithoutClaimsValidation is an option to disable claims validation. This
option should only be used if you exactly know what you are doing.
WithPaddingAllowed will enable the codec used for decoding JWTs to allow
padding. 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.
WithStrictDecoding 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.
WithSubject configures the validator to require the specified subject in the
`sub` claim. Validation will fail if a different subject is specified in the
token or the `sub` claim is missing.
NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is
application-specific. Since this validation API is helping developers in
writing secure application, we decided to REQUIRE the existence of the claim,
if a subject is expected.
WithTimeFunc returns the ParserOption for specifying the time func. The
primary use-case for this is testing. If you are looking for a way to account
for clock-skew, WithLeeway should be used instead.
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/.
errorIfFalse returns the error specified in err, if the value is true.
Otherwise, nil is returned.
errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is
true. Otherwise, nil is returned.
joinErrors joins together multiple errors. Useful for scenarios where
multiple errors next to each other occur, e.g., in claims validation.
newError creates a new error message with a detailed error message. The
message will be prefixed with the contents of the supplied error type.
Additionally, more errors, that provide more context can be supplied which
will be appended to the message. This makes use of Go 1.20's possibility to
include more than one %w formatting directive in [fmt.Errorf].
For example,
newError("no keyfunc was provided", ErrTokenUnverifiable)
will produce the error string
"token is unverifiable: no keyfunc was provided"
newNumericDateFromSeconds creates a new *NumericDate out of a float64 representing a
UNIX epoch with the float fraction representing non-integer seconds.
splitToken splits a token string into three parts: header, claims, and signature. It will only
return true if the token contains exactly two delimiters and three parts. In all other cases, it
will return nil parts and false.
Package-Level Variables (total 45, in which 43 are exported)
Sadly this is missing from crypto/ecdsa compared to crypto/rsa
MarshalSingleStringAsArray modifies the behavior 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
behavior 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.
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
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.
The pages are generated with Goldsv0.7.6. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.