jwt

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2020 License: MIT Imports: 14 Imported by: 17

README

jwt

Build Status GoDoc Go Report Card Coverage

JSON Web Tokens for Go

Features

  • Simple API.
  • Optimized for speed.
  • Dependency-free.

Install

Go version 1.13

go get github.com/cristalhq/jwt

Example

signer := jwt.NewHS256([]byte(`secret`))
builder := jwt.NewTokenBuilder(signer)

claims := &jwt.StandardClaims{
    Audience: []string{"admin"},
    ID:       "random-unique-string",
}
token, _ := builder.Build(claims)

raw := token.Raw() // JWT signed token

Also see examples: build, parse, validate.

Documentation

See these docs.

License

MIT License.

Documentation

Index

Constants

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

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

	// ErrInvalidSignature signature wasn't correct.
	ErrInvalidSignature = Error("jwt: signature is invalid")
)

Build and parse errors.

View Source
const (
	// ErrTokenExpired is the error when token is expited.
	ErrTokenExpired = Error("jwt: token has expited")

	// ErrAudValidation is the error for an invalid "aud" claim.
	ErrAudValidation = Error("jwt: aud claim is invalid")

	// ErrExpValidation is the error for an invalid "exp" claim.
	ErrExpValidation = Error("jwt: exp claim is invalid")

	// ErrIatValidation is the error for an invalid "iat" claim.
	ErrIatValidation = Error("jwt: iat claim is invalid")

	// ErrIssValidation is the error for an invalid "iss" claim.
	ErrIssValidation = Error("jwt: iss claim is invalid")

	// ErrJtiValidation is the error for an invalid "jti" claim.
	ErrJtiValidation = Error("jwt: jti claim is invalid")

	// ErrNbfValidation is the error for an invalid "nbf" claim.
	ErrNbfValidation = Error("jwt: nbf claim is invalid")

	// ErrSubValidation is the error for an invalid "sub" claim.
	ErrSubValidation = Error("jwt: sub claim is invalid")
)

Validation errors.

Variables

This section is empty.

Functions

func BuildBytes

func BuildBytes(signer Signer, claims BinaryMarshaler) ([]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 (
	NoEncryption Algorithm = "none"

	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 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 BinaryMarshaler

type BinaryMarshaler interface {
	MarshalBinary() (data []byte, err error)
}

BinaryMarshaler a marshaling interface for user claims.

type Check

type Check func(claims *StandardClaims) error

Check used to validate StandardClaims.

func AudienceChecker

func AudienceChecker(aud Audience) Check

AudienceChecker validates the "aud" claim.

func ExpirationTimeChecker

func ExpirationTimeChecker(now time.Time) Check

ExpirationTimeChecker validates the "exp" claim.

func IDChecker

func IDChecker(jti string) Check

IDChecker validates the "jti" claim.

func IssuedAtChecker

func IssuedAtChecker(now time.Time) Check

IssuedAtChecker validates the "iat" claim.

func IssuerChecker

func IssuerChecker(iss string) Check

IssuerChecker validates the "iss" claim.

func NotBeforeChecker

func NotBeforeChecker(now time.Time) Check

NotBeforeChecker validates the "nbf" claim.

func SubjectChecker

func SubjectChecker(sub string) Check

SubjectChecker validates the "sub" claim.

func ValidAtChecker

func ValidAtChecker(now time.Time) Check

ValidAtChecker validates whether the token is valid at the specified time, based on the values of the IssuedAt, NotBefore and ExpiresAt claims in the claims.

func ValidAtNowChecker

func ValidAtNowChecker() Check

ValidAtNowChecker validates whether the token is valid at the current time, based on the values of the IssuedAt, NotBefore and ExpiresAt claims in the claims.

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"` // type of JWS: it can only be "JWT" here
	ContentType string    `json:"cty,omitempty"`
	KeyID       string    `json:"kid,omitempty"`
}

Header stores JWT header data. see https://tools.ietf.org/html/rfc7515 and https://tools.ietf.org/html/rfc7519

func (Header) MarshalJSON

func (h Header) MarshalJSON() (data []byte, err error)

MarshalJSON implements json.Marshaler interface.

type Signer

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

Signer used to sign and verify tokens.

func NewES256

func NewES256(publicKey *ecdsa.PublicKey, privateKey *ecdsa.PrivateKey) (Signer, error)

NewES256 returns new HMAC Signer using RSA and SHA256 hash.

Both public and private keys must not be nil.

func NewES384

func NewES384(publicKey *ecdsa.PublicKey, privateKey *ecdsa.PrivateKey) (Signer, error)

NewES384 returns new HMAC Signer using RSA and SHA384 hash.

Both public and private keys must not be nil.

func NewES512

func NewES512(publicKey *ecdsa.PublicKey, privateKey *ecdsa.PrivateKey) (Signer, error)

NewES512 returns new HMAC Signer using RSA and SHA512 hash.

Both public and private keys must not be nil.

func NewEdDSA

func NewEdDSA(publicKey ed25519.PublicKey, privateKey ed25519.PrivateKey) (Signer, error)

NewEdDSA returns new signer using EdDSA algorithm.

Both public and private keys must not be nil.

func NewHS256

func NewHS256(key []byte) (Signer, error)

NewHS256 returns new HMAC Signer using SHA256 hash.

func NewHS384

func NewHS384(key []byte) (Signer, error)

NewHS384 returns new HMAC Signer using SHA384 hash.

func NewHS512

func NewHS512(key []byte) (Signer, error)

NewHS512 returns new HMAC Signer using SHA512 hash.

func NewNoEncrypt

func NewNoEncrypt() Signer

NewNoEncrypt returns new Signer without encryption. SHOULD NOT BE USED.

func NewPS256

func NewPS256(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) (Signer, error)

NewPS256 returns new PS256 Signer using RSA PSS and SHA256 hash.

Both public and private keys must not be nil.

func NewPS384

func NewPS384(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) (Signer, error)

NewPS384 returns new PS384 Signer using RSA PSS and SHA384 hash.

Both public and private keys must not be nil.

func NewPS512

func NewPS512(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) (Signer, error)

NewPS512 returns new PS512 Signer using RSA PSS and SHA512 hash.

Both public and private keys must not be nil.

func NewRS256

func NewRS256(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) (Signer, error)

NewRS256 returns new RSA Signer using RSA and SHA256 hash.

Both public and private keys must not be nil.

func NewRS384

func NewRS384(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) (Signer, error)

NewRS384 returns new RSA Signer using RSA and SHA384 hash.

Both public and private keys must not be nil.

func NewRS512

func NewRS512(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) (Signer, error)

NewRS512 returns new RSA Signer using RSA and SHA512 hash.

Both public and private keys must not be nil.

type StandardClaims

type StandardClaims struct {
	// Audience claim identifies the recipients that the JWT is intended for.
	Audience Audience `json:"aud,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 Timestamp `json:"exp,omitempty"`

	// ID claim provides a unique identifier for the JWT.
	ID string `json:"jti,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 Timestamp `json:"iat,omitempty"`

	// Issuer claim identifies the principal that issued the JWT.
	// Use of this claim is OPTIONAL.
	Issuer string `json:"iss,omitempty"`

	// NotBefore claim identifies the time before which the JWT MUST NOT be accepted for processing.
	// Use of this claim is OPTIONAL.
	NotBefore Timestamp `json:"nbf,omitempty"`

	// Subject claim identifies the principal that is the subject of the JWT.
	// Use of this claim is OPTIONAL.
	Subject string `json:"sub,omitempty"`
}

StandardClaims https://tools.ietf.org/html/rfc7519#section-4.1

func (StandardClaims) HasPassedNotBefore

func (sc StandardClaims) HasPassedNotBefore(now time.Time) bool

HasPassedNotBefore returns true if the token activation is used after the given time.

func (StandardClaims) IsExpired

func (sc StandardClaims) IsExpired(now time.Time) bool

IsExpired returns true if the token is expired.

func (StandardClaims) IsID

func (sc StandardClaims) IsID(id string) bool

IsID returns true if claims has the given id.

func (StandardClaims) IsIssuedBefore

func (sc StandardClaims) IsIssuedBefore(now time.Time) bool

IsIssuedBefore returns true if the token was issued before of given time.

func (StandardClaims) IsIssuedBy

func (sc StandardClaims) IsIssuedBy(issuers ...string) bool

IsIssuedBy returns true if the token was issued by any of given issuers.

func (StandardClaims) IsPermittedFor

func (sc StandardClaims) IsPermittedFor(audience string) bool

IsPermittedFor returns true if claims is allowed to be used by the audience.

func (StandardClaims) IsSubject

func (sc StandardClaims) IsSubject(subject string) bool

IsSubject returns true if claims has the given subject.

func (StandardClaims) MarshalBinary

func (sc StandardClaims) MarshalBinary() (data []byte, err error)

MarshalBinary default marshaling to JSON.

type Timestamp

type Timestamp int64

Timestamp represents time as number of seconds from 1970-01-01T00:00:00Z UTC until the specified moment.

func (Timestamp) Time

func (t Timestamp) Time() time.Time

Time used to convert int64 to time.Time.

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

type Token

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

Token represents a JWT token.

func Build

func Build(signer Signer, claims BinaryMarshaler) (*Token, error)

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

func BuildWithHeader

func BuildWithHeader(signer Signer, header Header, claims BinaryMarshaler) (*Token, error)

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

func Parse

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

Parse decodes a token from a raw bytes.

func ParseAndVerify

func ParseAndVerify(raw []byte, signer Signer) (*Token, error)

ParseAndVerify decodes a token and verifies it's signature with a given signer.

func ParseAndVerifyString

func ParseAndVerifyString(raw string, signer Signer) (*Token, error)

ParseAndVerifyString decodes a token and verifies it's signature with a given signer.

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) InsecureString

func (t Token) InsecureString() string

InsecureString returns token as is, with a signature (which may be sensitive).

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) Signature

func (t Token) Signature() []byte

Signature returns token's signature.

func (Token) String

func (t Token) String() string

String returns token as string, without a signature (replaced with `.<signature>`).

type TokenBuilder

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

TokenBuilder is used to create a new token.

func NewTokenBuilder

func NewTokenBuilder(signer Signer) *TokenBuilder

NewTokenBuilder returns new instance of TokenBuilder.

func (*TokenBuilder) Build

func (b *TokenBuilder) Build(claims BinaryMarshaler) (*Token, error)

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

func (*TokenBuilder) BuildBytes

func (b *TokenBuilder) BuildBytes(claims BinaryMarshaler) ([]byte, error)

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

type Validator

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

Validator used to validate StandardClaims.

func NewValidator

func NewValidator(checks ...Check) *Validator

NewValidator returns new instance of validator.

func (Validator) Validate

func (v Validator) Validate(claims *StandardClaims) error

Validate given claims and return first error.

func (Validator) ValidateAll

func (v Validator) ValidateAll(claims *StandardClaims) []error

ValidateAll will run all the checks and return a slice of errors, if any.

Jump to

Keyboard shortcuts

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