jwt

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2019 License: BSL-1.0 Imports: 6 Imported by: 0

README

Modular JWT / JWS provider in Golang

CircleCI Codecov Codacy GoDoc

This packages implements JSON Web Token as defined in RFC 7519 in Go.

It is build with a modular architecture to make it easy to adapt to most use cases.

For this reason all verification of signatures and contents is implemented independently and does explicitly have to be activated.

All tokens decoded by this package will automatically be validated using the activated signature and content verification providers. To check if the token is valid use token.Valid() which returns a boolean. If you want to know the exact error, use token.ValidationError().

The default algorithms for signature verification specified in RFC7518 and RFC8037 can be found in sub-packages in this repository.

EdDSA with Ed25519 and Ed448 (unstable), HMAC-SHA2, RSA PKCS#1 v1.5, RSA-PSS and ECDSA can all be found in the respective folders.

You may add a signature provider by calling AddSignatureProvider(name string, provider SignatureProvider) error with name being the value of the alg header this algorithm uses and alg being a properly initialized instance of the respective algorithm. To enable signing and select the algorithm to use, call SetSigningAlgorithm(name string) error with the name of the algorithm to use.

The main package includes some implementations of content validation providers in contentValidation.go. To add a content validator, call AddValidationProvider(name string, provider ContentValidationProvider) error with a name of your choosing and the initialized provider. It will automatically be used to validate all tokens that are decoded after adding it.

In case the providers included in this package do not fit your needs, you can always implement your own. For details see API.md.

Data structures

JWTs are stored as a struct with the following layout

type JWT struct {
	Header struct {
		Typ string // Type of the token, has to be JWT.
		Alg string // Algorithm used to sign the token (this package signs using EdDSA).
		Kid string // Key ID of the key used to sign the token.
		Jku string // URL presenting public key necessary for validation.
	}
	Content []byte // Encoded JSON as specified in RFC 7519 (Should be based on map or struct in Go)
}

Due to the header being a struct some values may be ignored when decoding.

Usage

Generating a new JWT

Creating a JWT is quite easy. You just have to supply your content encoded as JSON and this package will generate a JWT for you.

jwt.New(content []byte) (JWT, error)
Encoding a JWT

To actually use a JWT you will have to encode it. This is done by simply calling Encode on the JWT you created.

Please note that you will need to add a signature provider first and also set the singing provider to use.

token.Encode() ([]byte, error)
Decoding a JWT

To validate a JWT you will first have to decode it. Just supply it to the Decode function.

jwt.Decode(encodedtoken []byte) (JWT, error)
Validating the hash

When decoding a JWT, it is automatically validated but you will have to retieve the result using:

token.Valid() bool
token.ValidationError() error

Keep in mind that this only checks if the token was valid when it was decoded and also only using the validation providers registered at that time. You will also need to add the signature validation provider and add the necessary keys before decoding the token or it will be treated as invalid.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddSignatureProvider

func AddSignatureProvider(name string, provider SignatureProvider) error

AddSignatureProvider tries to add the signature provider to the list but fails when one with the same name already exists.

func AddValidationProvider

func AddValidationProvider(name string, provider ContentValidationProvider) error

AddValidationProvider adds a content validation provider

func RemoveSignatureProvider

func RemoveSignatureProvider(name string)

RemoveSignatureProvider removes a signature provider by name

func RemoveValidationProvider

func RemoveValidationProvider(name string)

RemoveValidationProvider removes a content validation provider by name

func SetSignatureProvider

func SetSignatureProvider(name string, provider SignatureProvider)

SetSignatureProvider sets the signature provider ignoring previous settings for the same name.

func SetSigningAlgorithm

func SetSigningAlgorithm(name string) error

SetSigningAlgorithm sets the default algorithm that will be used with Encode and by the Marshalers for encoding

Types

type AudienceValidationProvider

type AudienceValidationProvider struct {
	ExpectedAudience string
}

AudienceValidationProvider checks whether the token is for the correct audience. It should be initialized with an expected audience and will return an error when a different audience is encountered.

func (AudienceValidationProvider) Validate

func (p AudienceValidationProvider) Validate(c []byte) error

Validate will be called during validation of a token

type ContentValidationProvider

type ContentValidationProvider interface {
	Validate([]byte) error
}

ContentValidationProvider is an interface for verification providers used to validate the content of a JWT

type ExpiresValidationProvider

type ExpiresValidationProvider struct {
	Tolerance int64
}

ExpiresValidationProvider can be used to validate that the token is currently valid. It can be initialized with a tolerance that can compensate for slight differences in clocks.

func (ExpiresValidationProvider) Validate

func (p ExpiresValidationProvider) Validate(c []byte) error

Validate will be called during validation of a token

type Header struct {
	Typ string `json:"typ"`
	Alg string `json:"alg"`
	Kid string `json:"kid,omitempty"`
	Jku string `json:"jku,omitempty"`
	Crv string `json:"crv,omitempty"`
}

Header contains the header data of a JSON web token

type IssuedAtValidationProvider

type IssuedAtValidationProvider struct {
	Tolerance    int64
	ExpiresAfter int64
}

IssuedAtValidationProvider can be used that the token has been issued in a specific timeframe. It should be initialized with an amount of seconds after which tokens expire and optionally also a tolerance. Important: This provider also checks whether issued at timestamp is in the future and returns an error in that case.

func (IssuedAtValidationProvider) Validate

func (p IssuedAtValidationProvider) Validate(c []byte) error

Validate will be called during validation of a token

type IssuerValidationProvider

type IssuerValidationProvider struct {
	Issuers   []string
	Whitelist bool
}

IssuerValidationProvider validates the issuer of a JWT. It should be initialized with a slice of issuers. By default it considers the slice a blacklist. This can be changed by setting whilelist to true.

func (IssuerValidationProvider) Validate

func (p IssuerValidationProvider) Validate(c []byte) error

Validate will be called during validation of a token

type JWT

type JWT struct {
	Header  Header
	Content []byte
	// contains filtered or unexported fields
}

JWT contains the decoded header and encoded content of a JSON web token

func Decode

func Decode(in []byte) (data JWT, err error)

Decode decodes a JWT and check it's validity (use Validate() on JWT to see if it is valid)

func New

func New(content []byte) JWT

New returns a new JWT containing content Content has to be encoded JSON

func (JWT) Encode

func (t JWT) Encode() ([]byte, error)

Encode a JWT to a byte slice

func (JWT) MarshalBinary

func (jwt JWT) MarshalBinary() ([]byte, error)

MarshalBinary provides encoding.BinaryMarshaler

func (JWT) MarshalText

func (jwt JWT) MarshalText() ([]byte, error)

MarshalText provides encoding.TextMarshaler

func (*JWT) UnmarshalBinary

func (jwt *JWT) UnmarshalBinary(in []byte) error

UnmarshalBinary provides encoding.BinaryUnmarshaler

func (*JWT) UnmarshalText

func (jwt *JWT) UnmarshalText(in []byte) error

UnmarshalText provides encoding.TextUnmarshaler

func (JWT) Valid

func (jwt JWT) Valid() bool

Valid returns whether the token is valid or not

func (JWT) ValidationError

func (jwt JWT) ValidationError() error

ValidationError returns the error that occurred during validation or nil

type NotBeforeValidationProvider

type NotBeforeValidationProvider struct {
	Tolerance int64
}

NotBeforeValidationProvider can be used to validate that the token is currently valid. It can be initialized with a tolerance that can compensate for slight differences in clocks.

func (NotBeforeValidationProvider) Validate

func (p NotBeforeValidationProvider) Validate(c []byte) error

Validate will be called during validation of a token

type SignatureProvider

type SignatureProvider interface {
	Sign([]byte) ([]byte, error)
	Verify([]byte, []byte, Header) error
	Header(*Header)
}

SignatureProvider is an interface for algorithms used to sign and validate a JWS

type TokenIDValidationProvider

type TokenIDValidationProvider struct {
	ForbiddenTokenIDs []string
}

TokenIDValidationProvider can be used to blacklist some tokens. It should be initialized with a slice of forbidden token IDs and will return an error when one of those IDs in encountered.

func (TokenIDValidationProvider) Validate

func (p TokenIDValidationProvider) Validate(c []byte) error

Validate will be called during validation of a token

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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