jwt
packagemoduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
jwt-go
Ago (or 'golang' for search engine friendliness)implementation ofJSON WebTokens.
Starting withv4.0.0this project adds Go module support, but maintains backward compatibility witholderv3.x.y
tags and upstreamgithub.com/dgrijalva/jwt-go
. See theMIGRATION_GUIDE.md
for more information. Versionv5.0.0 introduces major improvements to the validation of tokens, but is notentirely backward compatible.
After the original author of the library suggested migrating the maintenanceof
jwt-go
, a dedicated team of open source maintainers decided to clone theexisting library into this repository. Seedgrijalva/jwt-go#462 for adetailed discussion on this topic.
SECURITY NOTICE: Some older versions of Go have a security issue in thecrypto/elliptic. The recommendation is to upgrade to at least 1.15 See issuedgrijalva/jwt-go#216 for moredetail.
SECURITY NOTICE: It's important that youvalidate thealg
presented iswhat youexpect.This library attempts to make it easy to do the right thing by requiring keytypes to match the expected alg, but you should take the extra step to verify it inyour usage. See the examples provided.
Supported Go versions
Our support of Go versions is aligned with Go'sversion releasepolicy. So we will support a majorversion of Go until there are two newer major releases. We no longer supportbuilding jwt-go with unsupported Go versions, as these contain securityvulnerabilities that will not be fixed.
What the heck is a JWT?
JWT.io hasa great introduction to JSON WebTokens.
In short, it's a signed JSON object that does something useful (for example,authentication). It's commonly used forBearer
tokens in Oauth 2. A token ismade of three parts, separated by.
's. The first two parts are JSON objects,that have beenbase64urlencoded. The last part is the signature, encoded the same way.
The first part is called the header. It contains the necessary information forverifying the last part, the signature. For example, which encryption methodwas used for signing and what key was used.
The part in the middle is the interesting bit. It's called the Claims andcontains the actual stuff you care about. Refer toRFC7519 for information aboutreserved keys and the proper way to add your own.
What's in the box?
This library supports the parsing and verification as well as the generation andsigning of JWTs. Current supported signing algorithms are HMAC SHA, RSA,RSA-PSS, and ECDSA, though hooks are present for adding your own.
Installation Guidelines
- To install the jwt package, you first need to haveGo installed, then you can use the commandbelow to add
jwt-go
as a dependency in your Go program.
go get -u github.com/golang-jwt/jwt/v5
- Import it in your code:
import "github.com/golang-jwt/jwt/v5"
Usage
A detailed usage guide, including how to sign and verify tokens can be found onourdocumentation website.
Examples
Seethe project documentationfor examples of usage:
- Simple example of parsing and validating atoken
- Simple example of building and signing atoken
- Directory ofExamples
Compliance
This library was last reviewed to comply withRFC7519 dated May 2015 with a fewnotable differences:
- In order to protect against accidental use ofUnsecuredJWTs, tokens using
alg=none
will only be accepted if the constantjwt.UnsafeAllowNoneSignatureType
is provided as the key.
Project Status & Versioning
This library is considered production ready. Feedback and feature requests areappreciated. The API should be considered stable. There should be very fewbackward-incompatible changes outside of major version updates (and only withgood reason).
This project usesSemantic Versioning 2.0.0. Accepted pullrequests will land onmain
. Periodically, versions will be tagged frommain
. You can find all the releases onthe project releasespage.
BREAKING CHANGES: A full list of breaking changes is available inVERSION_HISTORY.md
. SeeMIGRATION_GUIDE.md
for more information on updatingyour code.
Extensions
This library publishes all the necessary components for adding your own signingmethods or key functions. Simply implement theSigningMethod
interface andregister a factory method usingRegisterSigningMethod
or provide ajwt.Keyfunc
.
A common use case would be integrating with different 3rd party signatureproviders, like key management services from various cloud providers or HardwareSecurity Modules (HSMs) or to implement additional standards.
Extension | Purpose | Repo |
---|---|---|
GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go |
AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms |
JWKS | Provides support for JWKS (RFC 7517) as ajwt.Keyfunc | https://github.com/MicahParks/keyfunc |
Disclaimer: Unless otherwise specified, these integrations are maintained bythird parties and should not be considered as a primary offer by any of thementioned cloud providers
More
Go package documentation can be foundonpkg.go.dev. Additionaldocumentation can be found onour projectpage.
The command line utility included in this project (cmd/jwt) provides astraightforward example of token creation and parsing as well as a useful toolfor debugging your own integration. You'll also find several implementationexamples in the documentation.
golang-jwt incorporates a modified versionof the JWT logo, which is distributed under the terms of theMITLicense.
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 tokenres, err := http.PostForm(fmt.Sprintf("http://localhost:%v/authenticate", serverPort), url.Values{"user": {"test"},"pass": {"known"},})fatal(err)if res.StatusCode != 200 {fmt.Println("Unexpected status code", res.StatusCode)}// Read the token out of the response bodybuf, err := io.ReadAll(res.Body)fatal(err)_ = res.Body.Close()tokenString := strings.TrimSpace(string(buf))// Parse the tokentoken, err := jwt.ParseWithClaims(tokenString, &CustomClaimsExample{}, func(token *jwt.Token) (any, error) {// since we only use the one private key to sign the tokens,// we also only use its public counter part to verifyreturn verifyKey, nil})fatal(err)claims := token.Claims.(*CustomClaimsExample)fmt.Println(claims.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 processorreq, 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 bodybuf, err := io.ReadAll(res.Body)fatal(err)_ = res.Body.Close()fmt.Printf("%s", buf)
Output:Welcome, foo
Index¶
- Constants
- Variables
- func GetAlgorithms() (algs []string)
- func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error)
- func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error)
- func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error)
- func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error)
- func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)
- func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error)deprecated
- func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)
- func RegisterSigningMethod(alg string, f func() SigningMethod)
- type ClaimStrings
- type Claims
- type ClaimsValidator
- type Keyfunc
- type MapClaims
- func (m MapClaims) GetAudience() (ClaimStrings, error)
- func (m MapClaims) GetExpirationTime() (*NumericDate, error)
- func (m MapClaims) GetIssuedAt() (*NumericDate, error)
- func (m MapClaims) GetIssuer() (string, error)
- func (m MapClaims) GetNotBefore() (*NumericDate, error)
- func (m MapClaims) GetSubject() (string, error)
- type NumericDate
- type Parser
- func (p *Parser) DecodeSegment(seg string) ([]byte, error)
- func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error)
- func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error)
- func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error)
- type ParserOption
- func WithAllAudiences(aud ...string) ParserOption
- func WithAudience(aud ...string) ParserOption
- func WithExpirationRequired() ParserOption
- func WithIssuedAt() ParserOption
- func WithIssuer(iss string) ParserOption
- func WithJSONNumber() ParserOption
- func WithLeeway(leeway time.Duration) ParserOption
- func WithPaddingAllowed() ParserOption
- func WithStrictDecoding() ParserOption
- func WithSubject(sub string) ParserOption
- func WithTimeFunc(f func() time.Time) ParserOption
- func WithValidMethods(methods []string) ParserOption
- func WithoutClaimsValidation() ParserOption
- type RegisteredClaims
- func (c RegisteredClaims) GetAudience() (ClaimStrings, error)
- func (c RegisteredClaims) GetExpirationTime() (*NumericDate, error)
- func (c RegisteredClaims) GetIssuedAt() (*NumericDate, error)
- func (c RegisteredClaims) GetIssuer() (string, error)
- func (c RegisteredClaims) GetNotBefore() (*NumericDate, error)
- func (c RegisteredClaims) GetSubject() (string, error)
- type SigningMethod
- type SigningMethodECDSA
- type SigningMethodEd25519
- type SigningMethodHMAC
- type SigningMethodRSA
- type SigningMethodRSAPSS
- type Token
- 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)
- type TokenOption
- type Validator
- type VerificationKey
- type VerificationKeySet
Examples¶
Constants¶
const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed"
Variables¶
var (ErrNotECPublicKey =errors.New("key is not a valid ECDSA public key")ErrNotECPrivateKey =errors.New("key is not a valid ECDSA private key"))
var (ErrNotEdPrivateKey =errors.New("key is not a valid Ed25519 private key")ErrNotEdPublicKey =errors.New("key is not a valid Ed25519 public key"))
var (ErrInvalidKey =errors.New("key is invalid")ErrInvalidKeyType =errors.New("key is of invalid type")ErrHashUnavailable =errors.New("the requested hash function is unavailable")ErrTokenMalformed =errors.New("token is malformed")ErrTokenUnverifiable =errors.New("token is unverifiable")ErrTokenSignatureInvalid =errors.New("token signature is invalid")ErrTokenRequiredClaimMissing =errors.New("token is missing required claim")ErrTokenInvalidAudience =errors.New("token has invalid audience")ErrTokenExpired =errors.New("token is expired")ErrTokenUsedBeforeIssued =errors.New("token used before issued")ErrTokenInvalidIssuer =errors.New("token has invalid issuer")ErrTokenInvalidSubject =errors.New("token has invalid subject")ErrTokenNotValidYet =errors.New("token is not valid yet")ErrTokenInvalidId =errors.New("token has invalid id")ErrTokenInvalidClaims =errors.New("token has invalid claims")ErrInvalidType =errors.New("invalid type for claim"))
var (ErrKeyMustBePEMEncoded =errors.New("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key")ErrNotRSAPrivateKey =errors.New("key is not a valid RSA private key")ErrNotRSAPublicKey =errors.New("key is not a valid RSA public key"))
var (// Sadly this is missing from crypto/ecdsa compared to crypto/rsaErrECDSAVerification =errors.New("crypto/ecdsa: verification error"))
var (ErrEd25519Verification =errors.New("ed25519: verification error"))
var MarshalSingleStringAsArray =true
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 anarray of strings, even if it just contains one element, defaulting to thebehavior of the underlying []string. If it is set to false, it will serializeto a single string, if it contains one element. Otherwise, it will serializeto an array of strings.
var NoneSignatureTypeDisallowedErrorerror
var SigningMethodNone *signingMethodNone
SigningMethodNone implements the none signing method. This is required by the specbut you probably should never use it.
var TimePrecision =time.Second
TimePrecision sets the precision of times and dates within this library. Thishas an influence on the precision of times when comparing expiry or otherrelated time fields. Furthermore, it is also the precision of times whenserializing.
For backwards compatibility the default precision is set to seconds, so thatno fractional timestamps are generated.
Functions¶
funcGetAlgorithms¶
func GetAlgorithms() (algs []string)
GetAlgorithms returns a list of registered "alg" names
funcParseECPrivateKeyFromPEM¶
func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey,error)
ParseECPrivateKeyFromPEM parses a PEM encoded Elliptic Curve Private Key Structure
funcParseECPublicKeyFromPEM¶
ParseECPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key
funcParseEdPrivateKeyFromPEM¶
func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey,error)
ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key
funcParseEdPublicKeyFromPEM¶
ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key
funcParseRSAPrivateKeyFromPEM¶
func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey,error)
ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key
funcParseRSAPrivateKeyFromPEMWithPassworddeprecated
func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, passwordstring) (*rsa.PrivateKey,error)
ParseRSAPrivateKeyFromPEMWithPassword parses a PEM encoded PKCS1 or PKCS8 private key protected with password
Deprecated: This function is deprecated and should not be used anymore. It uses the deprecated x509.DecryptPEMBlockfunction, which was deprecated sinceRFC 1423 is regarded insecure by design. Unfortunately, there is no alternativein the Go standard library for now. Seehttps://github.com/golang/go/issues/8860.
funcParseRSAPublicKeyFromPEM¶
ParseRSAPublicKeyFromPEM parses a certificate or a PEM encoded PKCS1 or PKIX public key
funcRegisterSigningMethod¶
func RegisterSigningMethod(algstring, f func()SigningMethod)
RegisterSigningMethod registers the "alg" name and a factory function for signing method.This is typically done during init() in the method's implementation
Types¶
typeClaimStrings¶
type ClaimStrings []string
ClaimStrings is basically just a slice of strings, but it can be eitherserialized from a string array or just a string. This type is necessary,since the "aud" claim can either be a single string or an array.
func (ClaimStrings)MarshalJSON¶
func (sClaimStrings) MarshalJSON() (b []byte, errerror)
func (*ClaimStrings)UnmarshalJSON¶
func (s *ClaimStrings) UnmarshalJSON(data []byte) (errerror)
typeClaims¶
type Claims interface {GetExpirationTime() (*NumericDate,error)GetIssuedAt() (*NumericDate,error)GetNotBefore() (*NumericDate,error)GetIssuer() (string,error)GetSubject() (string,error)GetAudience() (ClaimStrings,error)}
Claims represent any form of a JWT Claims Set according tohttps://datatracker.ietf.org/doc/html/rfc7519#section-4. In order to have acommon basis for validation, it is required that an implementation is able tosupply at least the claim names provided inhttps://datatracker.ietf.org/doc/html/rfc7519#section-4.1 namely `exp`,`iat`, `nbf`, `iss`, `sub` and `aud`.
typeClaimsValidator¶
ClaimsValidator is an interface that can be implemented by custom claims whowish to execute any additional claims validation based onapplication-specific logic. The Validate function is then executed inaddition to the regular claims validation and any error returned is appendedto 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}
typeKeyfunc¶
Keyfunc will be used by the Parse methods as a callback function to supplythe key for verification. The function receives the parsed, but unverifiedToken. This allows you to use properties in the Header of the token (such as`kid`) to identify which key to use.
The returned any may be a single key or a VerificationKeySet containingmultiple keys.
typeMapClaims¶
MapClaims is a claims type that uses the map[string]any for JSONdecoding. This is the default claims type if you don't supply one
func (MapClaims)GetAudience¶
func (mMapClaims) GetAudience() (ClaimStrings,error)
GetAudience implements the Claims interface.
func (MapClaims)GetExpirationTime¶
func (mMapClaims) GetExpirationTime() (*NumericDate,error)
GetExpirationTime implements the Claims interface.
func (MapClaims)GetIssuedAt¶
func (mMapClaims) GetIssuedAt() (*NumericDate,error)
GetIssuedAt implements the Claims interface.
func (MapClaims)GetNotBefore¶
func (mMapClaims) GetNotBefore() (*NumericDate,error)
GetNotBefore implements the Claims interface.
func (MapClaims)GetSubject¶
GetSubject implements the Claims interface.
typeNumericDate¶
NumericDate represents a JSON numeric date value, as referenced athttps://datatracker.ietf.org/doc/html/rfc7519#section-2.
funcNewNumericDate¶
func NewNumericDate(ttime.Time) *NumericDate
NewNumericDate constructs a new *NumericDate from a standard library time.Time struct.It will truncate the timestamp according to the precision specified in TimePrecision.
func (NumericDate)MarshalJSON¶
func (dateNumericDate) MarshalJSON() (b []byte, errerror)
MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epochrepresented in NumericDate to a byte array, using the precision specified in TimePrecision.
func (*NumericDate)UnmarshalJSON¶
func (date *NumericDate) UnmarshalJSON(b []byte) (errerror)
UnmarshalJSON is an implementation of the json.RawMessage interface anddeserializes aNumericDate from a JSON representation, i.e. ajson.Number. This number represents an UNIX epoch with either integer ornon-integer seconds.
typeParser¶
type Parser struct {// contains filtered or unexported fields}
funcNewParser¶
func NewParser(options ...ParserOption) *Parser
NewParser creates a new Parser with the specified options
func (*Parser)DecodeSegment¶
DecodeSegment decodes a JWT specific base64url encoding. This function willtake into account whether theParser is configured with additional options,such asWithStrictDecoding orWithPaddingAllowed.
func (*Parser)Parse¶
Parse parses, validates, verifies the signature and returns the parsed token.keyFunc will receive the parsed token and should return the key for validating.
func (*Parser)ParseUnverified¶
func (p *Parser) ParseUnverified(tokenStringstring, claimsClaims) (token *Token, parts []string, errerror)
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 alreadybeen or will be checked elsewhere in the stack) and you want to extract values from it.
func (*Parser)ParseWithClaims¶
ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claimsinterface. This provides default values which can be overridden and allows a caller to use their own type, ratherthan 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 theproper memory for it before passing in the overall claims, otherwise you might run into a panic.
typeParserOption¶
type ParserOption func(*Parser)
ParserOption is used to implement functional-style options that modify thebehavior of the parser. To add new options, just create a function (ideallybeginning with With or Without) that returns an anonymous function that takesa *Parser type as input and manipulates its configuration accordingly.
funcWithAllAudiences¶added inv5.2.3
func WithAllAudiences(aud ...string)ParserOption
WithAllAudiences configures the validator to require all the specifiedaudiences in the `aud` claim. Validation will fail if the specified audiencesare not listed in the token or the `aud` claim is missing. Duplicates withinthe list are de-duplicated since internally, we use a map to look up theaudiences.
NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it isapplication-specific. Since this validation API is helping developers inwriting secure application, we decided to REQUIRE the existence of the claim,if an audience is expected.
funcWithAudience¶
func WithAudience(aud ...string)ParserOption
WithAudience configures the validator to require any of the specifiedaudiences in the `aud` claim. Validation will fail if the audience is notlisted in the token or the `aud` claim is missing.
NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it isapplication-specific. Since this validation API is helping developers inwriting secure application, we decided to REQUIRE the existence of the claim,if an audience is expected.
funcWithExpirationRequired¶added inv5.1.0
func WithExpirationRequired()ParserOption
WithExpirationRequired returns the ParserOption to make exp claim required.By default exp claim is optional.
funcWithIssuedAt¶
func WithIssuedAt()ParserOption
WithIssuedAt returns the ParserOption to enable verificationof issued-at.
funcWithIssuer¶
func WithIssuer(issstring)ParserOption
WithIssuer configures the validator to require the specified issuer in the`iss` claim. Validation will fail if a different issuer is specified in thetoken or the `iss` claim is missing.
NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it isapplication-specific. Since this validation API is helping developers inwriting secure application, we decided to REQUIRE the existence of the claim,if an issuer is expected.
funcWithJSONNumber¶
func WithJSONNumber()ParserOption
WithJSONNumber is an option to configure the underlying JSON parser withUseNumber.
funcWithLeeway¶
func WithLeeway(leewaytime.Duration)ParserOption
WithLeeway returns the ParserOption for specifying the leeway window.
funcWithPaddingAllowed¶
func WithPaddingAllowed()ParserOption
WithPaddingAllowed will enable the codec used for decoding JWTs to allowpadding. Note that the JWS RFC7515 states that the tokens will utilize aBase64url encoding with no padding. Unfortunately, some implementations ofJWT are producing non-standard tokens, and thus require support for decoding.
funcWithStrictDecoding¶
func WithStrictDecoding()ParserOption
WithStrictDecoding will switch the codec used for decoding JWTs into strictmode. In this mode, the decoder requires that trailing padding bits are zero,as described inRFC 4648 section 3.5.
funcWithSubject¶
func WithSubject(substring)ParserOption
WithSubject configures the validator to require the specified subject in the`sub` claim. Validation will fail if a different subject is specified in thetoken or the `sub` claim is missing.
NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it isapplication-specific. Since this validation API is helping developers inwriting secure application, we decided to REQUIRE the existence of the claim,if a subject is expected.
funcWithTimeFunc¶
func WithTimeFunc(f func()time.Time)ParserOption
WithTimeFunc returns the ParserOption for specifying the time func. Theprimary use-case for this is testing. If you are looking for a way to accountfor clock-skew, WithLeeway should be used instead.
funcWithValidMethods¶
func WithValidMethods(methods []string)ParserOption
WithValidMethods is an option to supply algorithm methods that the parserwill check. Only those methods will be considered valid. It is heavilyencouraged to use this option in order to prevent attacks such ashttps://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/.
funcWithoutClaimsValidation¶
func WithoutClaimsValidation()ParserOption
WithoutClaimsValidation is an option to disable claims validation. Thisoption should only be used if you exactly know what you are doing.
typeRegisteredClaims¶
type RegisteredClaims struct {// the `iss` (Issuer) claim. Seehttps://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1Issuerstring `json:"iss,omitempty"`// the `sub` (Subject) claim. Seehttps://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2Subjectstring `json:"sub,omitempty"`// the `aud` (Audience) claim. Seehttps://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3AudienceClaimStrings `json:"aud,omitempty"`// the `exp` (Expiration Time) claim. Seehttps://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4ExpiresAt *NumericDate `json:"exp,omitempty"`// the `nbf` (Not Before) claim. Seehttps://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5NotBefore *NumericDate `json:"nbf,omitempty"`// the `iat` (Issued At) claim. Seehttps://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6IssuedAt *NumericDate `json:"iat,omitempty"`// the `jti` (JWT ID) claim. Seehttps://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7IDstring `json:"jti,omitempty"`}
RegisteredClaims are a structured version of the JWT Claims Set,restricted to Registered Claim Names, as referenced athttps://datatracker.ietf.org/doc/html/rfc7519#section-4.1
This type can be used on its own, but then additional private andpublic claims embedded in the JWT will not be parsed. The typical use-casetherefore is to embedded this in a user-defined claim type.
See examples for how to use this with your own claim types.
func (RegisteredClaims)GetAudience¶
func (cRegisteredClaims) GetAudience() (ClaimStrings,error)
GetAudience implements the Claims interface.
func (RegisteredClaims)GetExpirationTime¶
func (cRegisteredClaims) GetExpirationTime() (*NumericDate,error)
GetExpirationTime implements the Claims interface.
func (RegisteredClaims)GetIssuedAt¶
func (cRegisteredClaims) GetIssuedAt() (*NumericDate,error)
GetIssuedAt implements the Claims interface.
func (RegisteredClaims)GetIssuer¶
func (cRegisteredClaims) GetIssuer() (string,error)
GetIssuer implements the Claims interface.
func (RegisteredClaims)GetNotBefore¶
func (cRegisteredClaims) GetNotBefore() (*NumericDate,error)
GetNotBefore implements the Claims interface.
func (RegisteredClaims)GetSubject¶
func (cRegisteredClaims) GetSubject() (string,error)
GetSubject implements the Claims interface.
typeSigningMethod¶
type SigningMethod interface {Verify(signingStringstring, sig []byte, keyany)error// Returns nil if signature is validSign(signingStringstring, keyany) ([]byte,error)// Returns signature or errorAlg()string// returns the alg identifier for this method (example: 'HS256')}
SigningMethod can be used add new methods for signing or verifying tokens. Ittakes a decoded signature as an input in the Verify function and produces asignature in Sign. The signature is then usually base64 encoded as part of aJWT.
funcGetSigningMethod¶
func GetSigningMethod(algstring) (methodSigningMethod)
GetSigningMethod retrieves a signing method from an "alg" string
typeSigningMethodECDSA¶
SigningMethodECDSA implements the ECDSA family of signing methods.Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification
var (SigningMethodES256 *SigningMethodECDSASigningMethodES384 *SigningMethodECDSASigningMethodES512 *SigningMethodECDSA)
Specific instances for EC256 and company
func (*SigningMethodECDSA)Alg¶
func (m *SigningMethodECDSA) Alg()string
typeSigningMethodEd25519¶
type SigningMethodEd25519 struct{}
SigningMethodEd25519 implements the EdDSA family.Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification
var (SigningMethodEdDSA *SigningMethodEd25519)
Specific instance for EdDSA
func (*SigningMethodEd25519)Alg¶
func (m *SigningMethodEd25519) Alg()string
typeSigningMethodHMAC¶
SigningMethodHMAC implements the HMAC-SHA family of signing methods.Expects key type of []byte for both signing and validation
var (SigningMethodHS256 *SigningMethodHMACSigningMethodHS384 *SigningMethodHMACSigningMethodHS512 *SigningMethodHMACErrSignatureInvalid =errors.New("signature is invalid"))
Specific instances for HS256 and company
func (*SigningMethodHMAC)Alg¶
func (m *SigningMethodHMAC) Alg()string
func (*SigningMethodHMAC)Sign¶
func (m *SigningMethodHMAC) Sign(signingStringstring, keyany) ([]byte,error)
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 'humanreadable' string using a subset of ASCII characters. To maximize entropy, youshould ideally be providing a []byte key which was produced from acryptographically random source, e.g. crypto/rand. Additional informationabout this, and why we intentionally are not supporting string as a key canbe found on our usage guidehttps://golang-jwt.github.io/jwt/usage/signing_methods/.
func (*SigningMethodHMAC)Verify¶
func (m *SigningMethodHMAC) Verify(signingStringstring, sig []byte, keyany)error
Verify implements token verification for the SigningMethod. Returns nil ifthe signature is valid. Key must be []byte.
Note it is not advised to provide a []byte which was converted from a 'humanreadable' string using a subset of ASCII characters. To maximize entropy, youshould ideally be providing a []byte key which was produced from acryptographically random source, e.g. crypto/rand. Additional informationabout this, and why we intentionally are not supporting string as a key canbe found on our usage guidehttps://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types.
typeSigningMethodRSA¶
SigningMethodRSA implements the RSA family of signing methods.Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation
var (SigningMethodRS256 *SigningMethodRSASigningMethodRS384 *SigningMethodRSASigningMethodRS512 *SigningMethodRSA)
Specific instances for RS256 and company
func (*SigningMethodRSA)Alg¶
func (m *SigningMethodRSA) Alg()string
typeSigningMethodRSAPSS¶
type SigningMethodRSAPSS struct {*SigningMethodRSAOptions *rsa.PSSOptions// VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS.// Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow//https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously.// Seehttps://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details.VerifyOptions *rsa.PSSOptions}
SigningMethodRSAPSS implements the RSAPSS family of signing methods signing methods
var (SigningMethodPS256 *SigningMethodRSAPSSSigningMethodPS384 *SigningMethodRSAPSSSigningMethodPS512 *SigningMethodRSAPSS)
Specific instances for RS/PS and company.
typeToken¶
type Token struct {Rawstring// Raw contains the raw token. Populated when you [Parse] a tokenMethodSigningMethod// Method is the signing method used or to be usedHeader map[string]any// Header is the first segment of the token in decoded formClaimsClaims// Claims is the second segment of the token in decoded formSignature []byte// Signature is the third segment of the token in decoded form. Populated when you Parse a tokenValidbool// Valid specifies if the token is valid. Populated when you Parse/Verify a token}
Token represents a JWT Token. Different fields will be used depending onwhether you're creating or parsing/verifying a token.
funcNew¶
func New(methodSigningMethod, opts ...TokenOption) *Token
New creates a newToken with the specified signing method and an empty mapof claims. Additional options can be specified, but are currently unused.
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 secrettokenString, err := token.SignedString(hmacSampleSecret)fmt.Println(tokenString, err)
Output:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU <nil>
funcNewWithClaims¶
func NewWithClaims(methodSigningMethod, claimsClaims, opts ...TokenOption) *Token
NewWithClaims creates a newToken with the specified signing method andclaims. Additional options can be specified, but are currently unused.
Example (CustomClaimsType)¶
Example creating a token using a custom claims type. The RegisteredClaims is embeddedin the custom type to allow for easy encoding, parsing and validation of registered claims.
mySigningKey := []byte("AllYourBase")type MyCustomClaims struct {Foo string `json:"foo"`jwt.RegisteredClaims}// Create claims with multiple fields populatedclaims := MyCustomClaims{"bar",jwt.RegisteredClaims{// A usual scenario is to set the expiration time relative to the current timeExpiresAt: 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"},},}fmt.Printf("foo: %v\n", claims.Foo)// Create claims while leaving out some of the optional fieldsclaims = MyCustomClaims{"bar",jwt.RegisteredClaims{// Also fixed dates can be used for the NumericDateExpiresAt: jwt.NewNumericDate(time.Unix(1516239022, 0)),Issuer: "test",},}token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)ss, err := token.SignedString(mySigningKey)fmt.Println(ss, err)
Output:foo: bareyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.xVuY2FZ_MRXMIEgVQ7J-TFtaucVFRXUzHm9LmV41goM <nil>
Example (RegisteredClaims)¶
Example (atypical) using the RegisteredClaims type by itself to parse a token.The RegisteredClaims type is designed to be embedded into your custom typesto provide standard validation features. You can use it alone, but there'sno way to retrieve other fields after parsing.See the CustomClaimsType example for intended usage.
mySigningKey := []byte("AllYourBase")// Create the Claimsclaims := &jwt.RegisteredClaims{ExpiresAt: jwt.NewNumericDate(time.Unix(1516239022, 0)),Issuer: "test",}token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)ss, err := token.SignedString(mySigningKey)fmt.Println(ss, err)
Output:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.0XN_1Tpp9FszFOonIBpwha0c_SfnNI22DhTnjMshPg8 <nil>
funcParse¶
func Parse(tokenStringstring, keyFuncKeyfunc, options ...ParserOption) (*Token,error)
Parse parses, validates, verifies the signature and returns the parsed token.keyFunc will receive the parsed token and should return the cryptographic keyfor verifying the signature. The caller is strongly encouraged to set theWithValidMethods option to validate the 'alg' claim in the token matches theexpected algorithm. For more details about the importance of validating the'alg' claim, seehttps://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
Example (ErrorChecking)¶
An example of parsing the error types using errors.Is.
// Token from another example. This token is expiredvar tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {return []byte("AllYourBase"), nil})switch {case token.Valid:fmt.Println("You look nice today")case errors.Is(err, jwt.ErrTokenMalformed):fmt.Println("That's not even a token")case errors.Is(err, jwt.ErrTokenSignatureInvalid):// Invalid signaturefmt.Println("Invalid signature")case errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet):// Token is either expired or not active yetfmt.Println("Timing is everything")default: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 exampletokenString := "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) (any, error) {// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")return hmacSampleSecret, nil}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))if err != nil {log.Fatal(err)}if claims, ok := token.Claims.(jwt.MapClaims); ok {fmt.Println(claims["foo"], claims["nbf"])} else {fmt.Println(err)}
Output:bar 1.4444784e+09
funcParseWithClaims¶
func ParseWithClaims(tokenStringstring, claimsClaims, keyFuncKeyfunc, options ...ParserOption) (*Token,error)
ParseWithClaims is a shortcut for NewParser().ParseWithClaims().
Note: If you provide a custom claim implementation that embeds one of thestandard claims (such as RegisteredClaims), make sure that a) you eitherembed a non-pointer version of the claims or b) if you are using a pointer,allocate the proper memory for it before passing in the overall claims,otherwise you might run into a panic.
Example (CustomClaimsType)¶
Example creating a token using a custom claims type. The RegisteredClaims is embeddedin the custom type to allow for easy encoding, parsing and validation of standard claims.
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA"type MyCustomClaims struct {Foo string `json:"foo"`jwt.RegisteredClaims}token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (any, error) {return []byte("AllYourBase"), nil})if err != nil {log.Fatal(err)} else if claims, ok := token.Claims.(*MyCustomClaims); ok {fmt.Println(claims.Foo, claims.Issuer)} else {log.Fatal("unknown claims type, cannot proceed")}
Output:bar test
Example (CustomValidation)¶
Example creating a token using a custom claims type and validation options.The RegisteredClaims is embedded in the custom type to allow for easyencoding, parsing and validation of standard claims and the functionCustomValidation is implemented.
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA"token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (any, error) {return []byte("AllYourBase"), nil}, jwt.WithLeeway(5*time.Second))if err != nil {log.Fatal(err)} else if claims, ok := token.Claims.(*MyCustomClaims); ok {fmt.Println(claims.Foo, claims.Issuer)} else {log.Fatal("unknown claims type, cannot proceed")}
Output:bar test
Example (ValidationOptions)¶
Example creating a token using a custom claims type and validation options. The RegisteredClaims is embeddedin the custom type to allow for easy encoding, parsing and validation of standard claims.
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA"type MyCustomClaims struct {Foo string `json:"foo"`jwt.RegisteredClaims}token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (any, error) {return []byte("AllYourBase"), nil}, jwt.WithLeeway(5*time.Second))if err != nil {log.Fatal(err)} else if claims, ok := token.Claims.(*MyCustomClaims); ok {fmt.Println(claims.Foo, claims.Issuer)} else {log.Fatal("unknown claims type, cannot proceed")}
Output:bar test
func (*Token)EncodeSegment¶
EncodeSegment encodes a JWT specific base64url encoding with paddingstripped. In the future, this function might take into account aTokenOption. Therefore, this function exists as a method ofToken, ratherthan a global function.
func (*Token)SignedString¶
SignedString creates and returns a complete, signed JWT. The token is signedusing the SigningMethod specified in the token. Please refer tohttps://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-typesfor an overview of the different signing methods and their respective keytypes.
func (*Token)SigningString¶
SigningString generates the signing string. This is the most expensive partof the whole deal. Unless you need this for something special, just gostraight for the SignedString.
typeTokenOption¶
type TokenOption func(*Token)
TokenOption is a reserved type, which provides some forward compatibility,if we ever want to introduce token creation-related options.
typeValidator¶added inv5.2.0
type Validator struct {// contains filtered or unexported fields}
Validator is the core of the new Validation API. It is automatically used byaParser during parsing and can be modified with various parser options.
TheNewValidator function should be used to create an instance of thisstruct.
funcNewValidator¶added inv5.2.0
func NewValidator(opts ...ParserOption) *Validator
NewValidator can be used to create a stand-alone validator with the suppliedoptions. This validator can then be used to validate already parsed claims.
Note: Under normal circumstances, explicitly creating a validator is notneeded and can potentially be dangerous; instead functions of theParserclass should be used.
TheValidator is only checking the *validity* of the claims, such as itsexpiration time, but it does NOT perform *signature verification* of thetoken.
func (*Validator)Validate¶added inv5.2.0
Validate validates the given claims. It will also perform any customvalidation if claims implements theClaimsValidator interface.
Note: It will NOT perform any *signature verification* on the token thatcontains the claims and expects that the [Claim] was already successfullyverified.
typeVerificationKey¶added inv5.1.0
VerificationKey represents a public or secret key for verifying a token's signature.
typeVerificationKeySet¶added inv5.1.0
type VerificationKeySet struct {Keys []VerificationKey}
VerificationKeySet is a set of public or secret keys. It is used by the parser to verify a token.