Documentation
¶
Overview ¶
Package jwt represents JSON Web Token for Go.
Builder, all Signers and Verifiers are safe for use by multiple goroutines simultaneously.
See [RFC 7519](https://tools.ietf.org/html/rfc7519) and see [jwt.io](https://jwt.io) for more.
Example (SignAndVerify) ¶
// create a Signer (HMAC in this example) key := []byte(`secret`) signer, err := jwt.NewSignerHS(jwt.HS256, key) checkErr(err) // create claims (you can create your own, see: ExampleBuilder_withUserClaims) claims := &jwt.RegisteredClaims{ Audience: []string{"admin"}, ID: "random-unique-string", } // create a Builder builder := jwt.NewBuilder(signer) // and build a Token token, err := builder.Build(claims) checkErr(err) // here is token as a string var _ string = token.String() // create a Verifier (HMAC in this example) verifier, err := jwt.NewVerifierHS(jwt.HS256, key) checkErr(err) // parse and verify a token tokenBytes := token.Bytes() newToken, err := jwt.Parse(tokenBytes, verifier) checkErr(err) // or just verify it's signature err = verifier.Verify(newToken) checkErr(err) // also you can parse without verify (NOT RECOMMENDED!) newToken, err = jwt.ParseNoVerify(tokenBytes) checkErr(err) // get REGISTERED claims var newClaims jwt.RegisteredClaims errClaims := json.Unmarshal(newToken.Claims(), &newClaims) checkErr(errClaims) // or parse only claims errParseClaims := jwt.ParseClaims(tokenBytes, verifier, &newClaims) checkErr(errParseClaims) // verify claims as you wish var _ bool = newClaims.IsForAudience("admin") var _ bool = newClaims.IsValidAt(time.Now())
Output:
Index ¶
- Variables
- func GenerateRandomBits(bits int) ([]byte, error)
- func ParseClaims(raw []byte, verifier Verifier, claims any) error
- type Algorithm
- type Audience
- type Builder
- type BuilderOption
- type ESAlg
- type EdDSAAlg
- type HSAlg
- type Header
- type NumericDate
- type PSAlg
- type RSAlg
- type RegisteredClaims
- func (sc *RegisteredClaims) IsForAudience(audience string) bool
- func (sc *RegisteredClaims) IsID(id string) bool
- func (sc *RegisteredClaims) IsIssuer(issuer string) bool
- func (sc *RegisteredClaims) IsSubject(subject string) bool
- func (sc *RegisteredClaims) IsValidAt(now time.Time) bool
- func (sc *RegisteredClaims) IsValidExpiresAt(now time.Time) bool
- func (sc *RegisteredClaims) IsValidIssuedAt(now time.Time) bool
- func (sc *RegisteredClaims) IsValidNotBefore(now time.Time) bool
- type Signer
- type Token
- func (t *Token) Bytes() []byte
- func (t *Token) Claims() json.RawMessage
- func (t *Token) ClaimsPart() []byte
- func (t *Token) DecodeClaims(dst any) error
- func (t *Token) Header() Header
- func (t *Token) HeaderPart() []byte
- func (t *Token) PayloadPart() []byte
- func (t *Token) Signature() []byte
- func (t *Token) SignaturePart() []byte
- func (t *Token) String() string
- type Verifier
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNilKey indicates that key is nil. ErrNilKey = errors.New("key is nil") // ErrInvalidKey indicates that key is not valid. ErrInvalidKey = errors.New("key is not valid") // ErrUnsupportedAlg indicates that given algorithm is not supported. ErrUnsupportedAlg = errors.New("algorithm is not supported") // ErrNotJWTType indicates that JWT token type is not JWT. // Deprecated: leftover after a wrong feature, present due to backward compatibility. ErrNotJWTType = errors.New("token of not JWT type") // ErrInvalidFormat indicates that token format is not valid. ErrInvalidFormat = errors.New("token format is not valid") // ErrAudienceInvalidFormat indicates that audience format is not valid. ErrAudienceInvalidFormat = errors.New("audience format is not valid") // ErrDateInvalidFormat indicates that date format is not valid. ErrDateInvalidFormat = errors.New("date is not valid") // ErrAlgorithmMismatch indicates that token is signed by another algorithm. ErrAlgorithmMismatch = errors.New("token is signed by another algorithm") // ErrInvalidSignature indicates that signature is not valid. ErrInvalidSignature = errors.New("signature is not valid") // ErrUninitializedToken indicates that token was not create with Parse func. ErrUninitializedToken = errors.New("token was not initialized") )
JWT sign, verify, build and parse errors.
Functions ¶
func GenerateRandomBits ¶
Generates a random key of the given bits length.
Types ¶
type Algorithm ¶
type Algorithm string
Algorithm for signing and verifying.
const ( EdDSA Algorithm = "EdDSA" HS256 Algorithm = "HS256" HS384 Algorithm = "HS384" HS512 Algorithm = "HS512" RS256 Algorithm = "RS256" RS384 Algorithm = "RS384" RS512 Algorithm = "RS512" ES256 Algorithm = "ES256" ES384 Algorithm = "ES384" ES512 Algorithm = "ES512" PS256 Algorithm = "PS256" PS384 Algorithm = "PS384" PS512 Algorithm = "PS512" )
Algorithm names for signing and verifying.
type Audience ¶
type Audience []string
Audience is a special claim that be a single string or an array of strings See: https://tools.ietf.org/html/rfc7519
func (Audience) MarshalJSON ¶
MarshalJSON implements a marshaling function for "aud" claim.
func (*Audience) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler interface.
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder is used to create a new token. Safe to use concurrently.
Example ¶
key := []byte(`secret`) signer, _ := jwt.NewSignerHS(jwt.HS256, key) builder := jwt.NewBuilder(signer) claims := &jwt.RegisteredClaims{ Audience: []string{"admin"}, ID: "random-unique-string", } token, err := builder.Build(claims) checkErr(err) fmt.Printf("Token %s\n", token.String()) fmt.Printf("Algorithm %s\n", token.Header().Algorithm) fmt.Printf("Type %s\n", token.Header().Type) fmt.Printf("Claims %s\n", token.Claims()) fmt.Printf("HeaderPart %s\n", token.HeaderPart()) fmt.Printf("ClaimsPart %s\n", token.ClaimsPart()) fmt.Printf("PayloadPart %s\n", token.PayloadPart()) fmt.Printf("SignaturePart %s\n", token.SignaturePart())
Output: Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0.uNaqGEggmy02lZq8FM7KoUKXhOy-zrSF7inYuzIET9o Algorithm HS256 Type JWT Claims {"jti":"random-unique-string","aud":"admin"} HeaderPart eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ClaimsPart eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0 PayloadPart eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0 SignaturePart uNaqGEggmy02lZq8FM7KoUKXhOy-zrSF7inYuzIET9o
Example (WithUserClaims) ¶
key := []byte(`secret`) signer, _ := jwt.NewSignerHS(jwt.HS256, key) builder := jwt.NewBuilder(signer) claims := &userClaims{ RegisteredClaims: jwt.RegisteredClaims{ Audience: []string{"admin"}, ID: "random-unique-string", }, IsAdministrator: true, Email: "foo@bar.baz", } token, err := builder.Build(claims) checkErr(err) fmt.Printf("Claims %v\n", string(token.Claims())) fmt.Printf("Payload %v\n", string(token.PayloadPart())) fmt.Printf("Token %v\n", string(token.Bytes()))
Output: Claims {"jti":"random-unique-string","aud":"admin","is_admin":true,"email":"foo@bar.baz"} Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIiwiaXNfYWRtaW4iOnRydWUsImVtYWlsIjoiZm9vQGJhci5iYXoifQ Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIiwiaXNfYWRtaW4iOnRydWUsImVtYWlsIjoiZm9vQGJhci5iYXoifQ.oKE62_k3bqAlKwdBJDBJq5DQ_0FvpNv6e1u6hF_ShQs
func NewBuilder ¶
func NewBuilder(signer Signer, opts ...BuilderOption) *Builder
NewBuilder returns new instance of Builder.
type BuilderOption ¶
type BuilderOption func(*Builder)
BuilderOption is used to modify builder properties.
func WithContentType ¶
func WithContentType(cty string) BuilderOption
WithContentType sets `cty` header for token.
type ESAlg ¶
type ESAlg struct {
// contains filtered or unexported fields
}
func NewSignerES ¶
func NewSignerES(alg Algorithm, key *ecdsa.PrivateKey) (*ESAlg, error)
NewSignerES returns a new ECDSA-based signer.
func NewVerifierES ¶
NewVerifierES returns a new ECDSA-based verifier.
type EdDSAAlg ¶
type EdDSAAlg struct {
// contains filtered or unexported fields
}
func NewSignerEdDSA ¶
func NewSignerEdDSA(key ed25519.PrivateKey) (*EdDSAAlg, error)
NewSignerEdDSA returns a new ed25519-based signer.
func NewVerifierEdDSA ¶
NewVerifierEdDSA returns a new ed25519-based verifier.
type HSAlg ¶
type HSAlg struct {
// contains filtered or unexported fields
}
func NewSignerHS ¶
NewSignerHS returns a new HMAC-based signer.
func NewVerifierHS ¶
NewVerifierHS returns a new HMAC-based verifier.
type Header ¶
type Header struct { Algorithm Algorithm `json:"alg"` Type string `json:"typ,omitempty"` // only "JWT" can be here ContentType string `json:"cty,omitempty"` KeyID string `json:"kid,omitempty"` }
Header representa JWT header data. See: https://tools.ietf.org/html/rfc7519#section-5, https://tools.ietf.org/html/rfc7517
func (Header) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
type NumericDate ¶
NumericDate represents date for StandardClaims See: https://tools.ietf.org/html/rfc7519#section-2
func NewNumericDate ¶
func NewNumericDate(t time.Time) *NumericDate
NewNumericDate creates a new NumericDate value from time.Time.
func (NumericDate) MarshalJSON ¶
func (t NumericDate) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface.
func (*NumericDate) UnmarshalJSON ¶
func (t *NumericDate) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface.
type PSAlg ¶
type PSAlg struct {
// contains filtered or unexported fields
}
func NewSignerPS ¶
func NewSignerPS(alg Algorithm, key *rsa.PrivateKey) (*PSAlg, error)
NewSignerPS returns a new RSA-PSS-based signer.
func NewVerifierPS ¶
NewVerifierPS returns a new RSA-PSS-based signer.
type RSAlg ¶
type RSAlg struct {
// contains filtered or unexported fields
}
func NewSignerRS ¶
func NewSignerRS(alg Algorithm, key *rsa.PrivateKey) (*RSAlg, error)
NewSignerRS returns a new RSA-based signer.
func NewVerifierRS ¶
NewVerifierRS returns a new RSA-based verifier.
type RegisteredClaims ¶
type RegisteredClaims struct { // ID claim provides a unique identifier for the JWT. ID string `json:"jti,omitempty"` // Audience claim identifies the recipients that the JWT is intended for. Audience Audience `json:"aud,omitempty"` // Issuer claim identifies the principal that issued the JWT. // Use of this claim is OPTIONAL. Issuer string `json:"iss,omitempty"` // Subject claim identifies the principal that is the subject of the JWT. // Use of this claim is OPTIONAL. Subject string `json:"sub,omitempty"` // ExpiresAt claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. // Use of this claim is OPTIONAL. ExpiresAt *NumericDate `json:"exp,omitempty"` // IssuedAt claim identifies the time at which the JWT was issued. // This claim can be used to determine the age of the JWT. // Use of this claim is OPTIONAL. IssuedAt *NumericDate `json:"iat,omitempty"` // NotBefore claim identifies the time before which the JWT MUST NOT be accepted for processing. // Use of this claim is OPTIONAL. NotBefore *NumericDate `json:"nbf,omitempty"` }
RegisteredClaims represents claims for JWT. See: https://tools.ietf.org/html/rfc7519#section-4.1
func (*RegisteredClaims) IsForAudience ¶
func (sc *RegisteredClaims) IsForAudience(audience string) bool
IsForAudience reports whether token has a given audience.
func (*RegisteredClaims) IsID ¶
func (sc *RegisteredClaims) IsID(id string) bool
IsID reports whether token has a given id.
func (*RegisteredClaims) IsIssuer ¶
func (sc *RegisteredClaims) IsIssuer(issuer string) bool
IsIssuer reports whether token has a given issuer.
func (*RegisteredClaims) IsSubject ¶
func (sc *RegisteredClaims) IsSubject(subject string) bool
IsSubject reports whether token has a given subject.
func (*RegisteredClaims) IsValidAt ¶
func (sc *RegisteredClaims) IsValidAt(now time.Time) bool
IsValidAt reports whether a token is valid at a given time.
func (*RegisteredClaims) IsValidExpiresAt ¶
func (sc *RegisteredClaims) IsValidExpiresAt(now time.Time) bool
IsValidExpiresAt reports whether a token isn't expired at a given time.
func (*RegisteredClaims) IsValidIssuedAt ¶
func (sc *RegisteredClaims) IsValidIssuedAt(now time.Time) bool
IsValidIssuedAt reports whether a token was created before a given time.
func (*RegisteredClaims) IsValidNotBefore ¶
func (sc *RegisteredClaims) IsValidNotBefore(now time.Time) bool
IsValidNotBefore reports whether a token isn't used before a given time.
type Token ¶
type Token struct {
// contains filtered or unexported fields
}
Token represents a JWT token. See: https://tools.ietf.org/html/rfc7519
func Parse ¶
Parse decodes a token and verifies it's signature.
Example ¶
rawToken := []byte(`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs`) key := []byte(`secret`) verifier, _ := jwt.NewVerifierHS(jwt.HS256, key) token, err := jwt.Parse(rawToken, verifier) checkErr(err) fmt.Printf("Algorithm %v\n", token.Header().Algorithm) fmt.Printf("Type %v\n", token.Header().Type) fmt.Printf("Claims %v\n", string(token.Claims())) fmt.Printf("Payload %v\n", string(token.PayloadPart())) fmt.Printf("Token %v\n", string(token.Bytes()))
Output: Algorithm HS256 Type JWT Claims {"aud":"admin","jti":"random-unique-string"} Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0 Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs
func ParseNoVerify ¶
ParseNoVerify decodes a token from a raw bytes. NOTE: Consider to use Parse with a verifier to verify token signature.
Example ¶
rawToken := []byte(`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs`) token, err := jwt.ParseNoVerify(rawToken) checkErr(err) fmt.Printf("Algorithm %v\n", token.Header().Algorithm) fmt.Printf("Type %v\n", token.Header().Type) fmt.Printf("Claims %v\n", string(token.Claims())) fmt.Printf("Payload %v\n", string(token.PayloadPart())) fmt.Printf("Token %v\n", string(token.Bytes()))
Output: Algorithm HS256 Type JWT Claims {"aud":"admin","jti":"random-unique-string"} Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0 Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs
func (*Token) ClaimsPart ¶
ClaimsPart returns token claims part.
func (*Token) DecodeClaims ¶
DecodeClaims into a given parameter.
func (*Token) HeaderPart ¶
HeaderPart returns token header part.
func (*Token) PayloadPart ¶
PayloadPart returns token payload part.
func (*Token) SignaturePart ¶
SignaturePart returns token signature part.