jwt

package module
v3.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 9, 2021 License: MIT Imports: 18 Imported by: 49

README

jwt

build-img pkg-img reportcard-img coverage-img

JSON Web Token for Go RFC 7519, also see jwt.io for more.

The latest version is v3.

Rationale

There are many JWT libraries, but many of them are hard to use (unclear or fixed API), not optimal (unneeded allocations + strange API). This library addresses all these issues. It's simple to read, to use, memory and CPU conservative.

Features

  • Simple API.
  • Clean and tested code.
  • Optimized for speed.
  • Concurrent-safe.
  • Dependency-free.
  • All well-known algorithms are supported
    • HMAC (HS)
    • RSA (RS)
    • RSA-PSS (PS)
    • ECDSA (ES)
    • EdDSA (EdDSA)
    • or your own!

Install

Go version 1.13+

GO111MODULE=on go get github.com/cristalhq/jwt/v3

Example

Build new token:

// 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: Example_BuildUserClaims)
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 byte slice
var _ []byte = token.Bytes() // or just token.String() for string

Parse and verify token:

// create a Verifier (HMAC in this example)
key := []byte(`secret`)
verifier, err := jwt.NewVerifierHS(jwt.HS256, key)
checkErr(err)

// parse a Token (by example received from a request)
tokenStr := `<header.payload.signature>`
token, err := jwt.ParseString(tokenStr)
checkErr(err)

// and verify it's signature
err = verifier.Verify(token.Payload(), token.Signature())
checkErr(err)

// also you can parse and verify together
newToken, err := jwt.ParseAndVerifyString(tokenStr, verifier)
checkErr(err)

// get standard claims
var newClaims jwt.StandardClaims
errClaims := json.Unmarshal(newToken.RawClaims(), &newClaims)
checkErr(errClaims)

// verify claims as you 
var _ bool = newClaims.IsForAudience("admin")
var _ bool = newClaims.IsValidAt(time.Now())

Also see examples: example_test.go.

Documentation

See these docs.

License

MIT License.

Documentation

Overview

Package jwt represents JSON Web Token for Go.

Builder, all the 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
// 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: Example_BuildUserClaims)
claims := &jwt.RegisteredClaims{
	Audience: []string{"admin"},
	ID:       "random-unique-string",
}

// create a Builder
builder := jwt.NewBuilder(signer)

// and build a Token
newToken, err := builder.Build(claims)
checkErr(err)

// here is token as byte slice
var _ []byte = newToken.Raw() // or just token.String() for string

// create a Verifier (HMAC in this example)
verifier, err := jwt.NewVerifierHS(jwt.HS256, key)
checkErr(err)

// parse a Token (by example received from a request)
tokenStr := newToken.String()
token, err := jwt.ParseAndVerifyString(tokenStr, verifier)
checkErr(err)

// and verify it's signature
err = verifier.Verify(token.Payload(), token.Signature())
checkErr(err)

// also you can parse and verify together
newToken, err = jwt.ParseAndVerifyString(tokenStr, verifier)
checkErr(err)

// get standard claims
var newClaims jwt.StandardClaims
errClaims := json.Unmarshal(newToken.RawClaims(), &newClaims)
checkErr(errClaims)

// verify claims as you
var _ bool = newClaims.IsForAudience("admin")
var _ bool = newClaims.IsValidAt(time.Now())
Output:

Index

Examples

Constants

View Source
const (
	// ErrNilKey indicates that key is nil.
	ErrNilKey = Error("jwt: key is nil")

	// ErrInvalidKey indicates that key is not valid.
	ErrInvalidKey = Error("jwt: key is not valid")

	// ErrUnsupportedAlg indicates that given algorithm is not supported.
	ErrUnsupportedAlg = Error("jwt: algorithm is not supported")

	// ErrInvalidFormat indicates that token format is not valid.
	ErrInvalidFormat = Error("jwt: token format is not valid")

	// ErrAudienceInvalidFormat indicates that audience format is not valid.
	ErrAudienceInvalidFormat = Error("jwt: audience format is not valid")

	// ErrDateInvalidFormat indicates that date format is not valid.
	ErrDateInvalidFormat = Error("jwt: date is not valid")

	// ErrAlgorithmMismatch indicates that token is signed by another algorithm.
	ErrAlgorithmMismatch = Error("jwt: token is signed by another algorithm")

	// ErrInvalidSignature indicates that signature is not valid.
	ErrInvalidSignature = Error("jwt: signature is not valid")
)

Build and parse errors.

Variables

This section is empty.

Functions

func BuildBytes

func BuildBytes(signer Signer, claims interface{}) ([]byte, error)

BuildBytes is used to create and encode JWT with a provided claims.

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.

func (Algorithm) String

func (a Algorithm) String() string

type Audience

type Audience []string

Audience is a special claim that be a single string or an array of strings see RFC 7519.

func (Audience) MarshalJSON

func (a Audience) MarshalJSON() ([]byte, error)

MarshalJSON implements a marshaling function for "aud" claim.

func (*Audience) UnmarshalJSON

func (a *Audience) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder is used to create a new token.

func NewBuilder

func NewBuilder(signer Signer, opts ...BuilderOption) *Builder

NewBuilder returns new instance of Builder.

func (*Builder) Build

func (b *Builder) Build(claims interface{}) (*Token, error)

Build used to create and encode JWT with a provided claims. If claims param is of type []byte or string then it's treated as a marshaled JSON. In other words you can pass already marshaled claims.

func (*Builder) BuildBytes

func (b *Builder) BuildBytes(claims interface{}) ([]byte, error)

BuildBytes used to create and encode JWT with a provided claims.

type BuilderOption added in v3.0.7

type BuilderOption func(*Builder)

BuilderOption is used to modify builder properties.

func WithContentType added in v3.0.7

func WithContentType(cty string) BuilderOption

WithContentType sets `cty` header for token.

func WithKeyID added in v3.0.7

func WithKeyID(kid string) BuilderOption

WithKeyID sets `kid` header for token.

type Error

type Error string

Error represents a JWT error.

func (Error) Error

func (e Error) Error() string
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

func (h *Header) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

type NumericDate

type NumericDate struct {
	time.Time
}

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 RegisteredClaims added in v3.0.8

type RegisteredClaims = StandardClaims

RegisteredClaims will replace StandardClaims in v4.

type Signer

type Signer interface {
	Algorithm() Algorithm
	SignSize() int
	Sign(payload []byte) ([]byte, error)
}

Signer is used to sign tokens.

func NewSignerES

func NewSignerES(alg Algorithm, key *ecdsa.PrivateKey) (Signer, error)

NewSignerES returns a new ECDSA-based signer.

func NewSignerEdDSA

func NewSignerEdDSA(key ed25519.PrivateKey) (Signer, error)

NewSignerEdDSA returns a new ed25519-based signer.

func NewSignerHS

func NewSignerHS(alg Algorithm, key []byte) (Signer, error)

NewSignerHS returns a new HMAC-based signer.

func NewSignerPS

func NewSignerPS(alg Algorithm, key *rsa.PrivateKey) (Signer, error)

NewSignerPS returns a new RSA-PSS-based signer.

func NewSignerRS

func NewSignerRS(alg Algorithm, key *rsa.PrivateKey) (Signer, error)

NewSignerRS returns a new RSA-based signer.

type StandardClaims

type StandardClaims 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"`
}

StandardClaims represents claims for JWT. See: https://tools.ietf.org/html/rfc7519#section-4.1

func (*StandardClaims) IsForAudience

func (sc *StandardClaims) IsForAudience(audience string) bool

IsForAudience reports whether token has a given audience.

func (*StandardClaims) IsID

func (sc *StandardClaims) IsID(id string) bool

IsID reports whether token has a given id.

func (*StandardClaims) IsIssuer

func (sc *StandardClaims) IsIssuer(issuer string) bool

IsIssuer reports whether token has a given issuer.

func (*StandardClaims) IsSubject

func (sc *StandardClaims) IsSubject(subject string) bool

IsSubject reports whether token has a given subject.

func (*StandardClaims) IsValidAt

func (sc *StandardClaims) IsValidAt(now time.Time) bool

IsValidAt reports whether a token is valid at a given time.

func (*StandardClaims) IsValidExpiresAt

func (sc *StandardClaims) IsValidExpiresAt(now time.Time) bool

IsValidExpiresAt reports whether a token isn't expired at a given time.

func (*StandardClaims) IsValidIssuedAt

func (sc *StandardClaims) IsValidIssuedAt(now time.Time) bool

IsValidIssuedAt reports whether a token was created before a given time.

func (*StandardClaims) IsValidNotBefore

func (sc *StandardClaims) 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 Build

func Build(signer Signer, claims interface{}) (*Token, error)

Build is used to create and encode JWT with a provided claims.

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("Algorithm %v\n", token.Header().Algorithm)
fmt.Printf("Type      %v\n", token.Header().Type)
fmt.Printf("Claims    %v\n", string(token.RawClaims()))
fmt.Printf("Payload   %v\n", string(token.Payload()))
fmt.Printf("Token     %v\n", string(token.Raw()))
Output:

Algorithm HS256
Type      JWT
Claims    {"jti":"random-unique-string","aud":"admin"}
Payload   eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0
Token     eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0.uNaqGEggmy02lZq8FM7KoUKXhOy-zrSF7inYuzIET9o

func Parse

func Parse(raw []byte) (*Token, error)

Parse decodes a token from a raw bytes.

Example
rawToken := []byte(`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs`)

token, err := jwt.Parse(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.RawClaims()))
fmt.Printf("Payload   %v\n", string(token.Payload()))
fmt.Printf("Token     %v\n", string(token.Raw()))
Output:

Algorithm HS256
Type      JWT
Claims    {"aud":"admin","jti":"random-unique-string"}
Payload   eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0
Token     eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs

func ParseAndVerify

func ParseAndVerify(raw []byte, verifier Verifier) (*Token, error)

ParseAndVerify 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.ParseAndVerify(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.RawClaims()))
fmt.Printf("Payload   %v\n", string(token.Payload()))
fmt.Printf("Token     %v\n", string(token.Raw()))
Output:

Algorithm HS256
Type      JWT
Claims    {"aud":"admin","jti":"random-unique-string"}
Payload   eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0
Token     eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs

func ParseAndVerifyString

func ParseAndVerifyString(raw string, verifier Verifier) (*Token, error)

ParseAndVerifyString decodes a token and verifies it's signature.

func ParseString

func ParseString(raw string) (*Token, error)

ParseString decodes a token.

func (*Token) Header

func (t *Token) Header() Header

Header returns token's header.

func (*Token) Payload

func (t *Token) Payload() []byte

Payload returns token's payload.

func (*Token) Raw

func (t *Token) Raw() []byte

Raw returns token's raw bytes.

func (*Token) RawClaims

func (t *Token) RawClaims() []byte

RawClaims returns token's claims as a raw bytes.

func (*Token) RawHeader

func (t *Token) RawHeader() []byte

RawHeader returns token's header raw bytes.

func (*Token) SecureString

func (t *Token) SecureString() string

SecureString returns token without a signature (replaced with `.<signature>`).

func (*Token) Signature

func (t *Token) Signature() []byte

Signature returns token's signature.

func (*Token) String

func (t *Token) String() string

type Verifier

type Verifier interface {
	Algorithm() Algorithm
	Verify(payload, signature []byte) error
}

Verifier is used to verify tokens.

func NewVerifierES

func NewVerifierES(alg Algorithm, key *ecdsa.PublicKey) (Verifier, error)

NewVerifierES returns a new ECDSA-based verifier.

func NewVerifierEdDSA

func NewVerifierEdDSA(key ed25519.PublicKey) (Verifier, error)

NewVerifierEdDSA returns a new ed25519-based verifier.

func NewVerifierHS

func NewVerifierHS(alg Algorithm, key []byte) (Verifier, error)

NewVerifierHS returns a new HMAC-based verifier.

func NewVerifierPS

func NewVerifierPS(alg Algorithm, key *rsa.PublicKey) (Verifier, error)

NewVerifierPS returns a new RSA-PSS-based signer.

func NewVerifierRS

func NewVerifierRS(alg Algorithm, key *rsa.PublicKey) (Verifier, error)

NewVerifierRS returns a new RSA-based verifier.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL