jwt

package module
v0.0.0-...-cd509b0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2015 License: Apache-2.0 Imports: 18 Imported by: 0

README

jwt

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.

The best way to understand how something functions is by taking it apart and putting it back together. This is a exploration in implementing a simple and concise encoder/decoder library for JWT.

Build Status GoDoc Coverage Status

Library Features

Feature Algorithm
👍 Sign 👍 HS256
👍 Verify 👍 HS384
🔴 iss check 👍 HS512
🔴 sub check 👍 RS256
🔴 aud check 👍 RS384
🔴 exp check 👍 RS512
🔴 nbf check 👍 ES256
🔴 iat check 👍 ES384
🔴 jti check 👍 ES512

Examples

Create token
payload := &struct {
	Payload
	Admin  bool `json:"admin"`
	UserID int  `json:"user_id"`
}{
	Payload: Payload{Issuer: "Ben Campbell"},
	Admin:   true,
	UserID:  1234,
}
tokenBuffer := bytes.NewBuffer(nil)

v := NewHSValidator(HS256)
v.Key = []byte("bogokey")

err := NewEncoder(tokenBuffer, v).Encode(payload)

if err != nil {
	panic(err)
}

fmt.Println(tokenBuffer.String())
// Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJCZW4gQ2FtcGJlbGwiLCJhZG1pbiI6dHJ1ZSwidXNlcl9pZCI6MTIzNH0.r4W8qDl8i8cUcRUxtA3hM0SZsLScHiBgBKZc_n_GrXI
}
Consume a token
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJCZW4gQ2FtcGJlbGwiLCJhZG1pbiI6dHJ1ZSwidXNlcl9pZCI6MTIzNH0.r4W8qDl8i8cUcRUxtA3hM0SZsLScHiBgBKZc_n_GrXI"

payload := &struct {
	Payload
	Admin  bool `json:"admin"`
	UserID int  `json:"user_id"`
}{}

v := NewHSValidator(HS256)
v.Key = []byte("bogokey")

err := NewDecoder(bytes.NewBufferString(token), v).Decode(payload)

if err != nil {
	panic(err)
}

fmt.Printf("%+v\n", payload)
// Output: &{Payload:{Issuer:Ben Campbell Subject: Audience: ExpirationTime:<nil> NotBefore:<nil> IssuedAt:<nil> JWTId: raw:[]} Admin:true UserID:1234}
References

Documentation

Index

Examples

Constants

View Source
const (
	// ES256 is the elliptic curve signing algorithm using 256 bits
	ES256 = "ES256"
	// ES384 is the elliptic curve signing algorithm using 384 bits
	ES384 = "ES384"
	// ES512 is the elliptic curve signing algorithm using 512 bits
	ES512 = "ES512"
	// HS256 is the HMAC SHA256 signing algorithm
	HS256 = "HS256"
	// HS384 is the HMAC SHA384 signing algorithm
	HS384 = "HS384"
	// HS512 is the HMAC SHA512 signing algorithm
	HS512 = "HS512"
	// None is the noop siging algorithm
	None = "none"
	// RS256 is a RSA algorithm using a SHA256 algorithm
	RS256 = "RS256"
	// RS384 is a RSA algorithm using a SHA384 algorithm
	RS384 = "RS384"
	// RS512 is a RSA algorithm using a SHA512 algorithm
	RS512 = "RS512"
)

Variables

View Source
var (
	// ErrMalformedToken represent errors where the given jwt is improperly formed
	ErrMalformedToken = errors.New("malformed Content")
	// ErrBadSignature represents errors where a signature is invalid
	ErrBadSignature = errors.New("invalid Signature")
	// ErrAlgorithmNotImplemented is thrown if a given jwt is using an algorithm not implemented
	ErrAlgorithmNotImplemented = errors.New("requested algorithm is not implemented")
)

Functions

func NewHSValidator

func NewHSValidator(algorithm Algorithm) hsValidator

Types

type Algorithm

type Algorithm string

An Algorithm describes the signing algorithm as defined by the jwt specficiation

type Decoder

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

A Decoder is a centeralized reader and key used to consume and verify a given jwt token.

Example
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJCZW4gQ2FtcGJlbGwiLCJhZG1pbiI6dHJ1ZSwidXNlcl9pZCI6MTIzNH0.r4W8qDl8i8cUcRUxtA3hM0SZsLScHiBgBKZc_n_GrXI"

payload := &struct {
	Payload
	Admin  bool `json:"admin"`
	UserID int  `json:"user_id"`
}{}

v := NewHSValidator(HS256)
v.Key = []byte("bogokey")

err := NewDecoder(bytes.NewBufferString(token), v).Decode(payload)

if err != nil {
	panic(err)
}

fmt.Printf("%+v\n", payload)
Output:

&{Payload:{Issuer:Ben Campbell Subject: Audience: ExpirationTime:<nil> NotBefore:<nil> IssuedAt:<nil> JWTId: raw:[]} Admin:true UserID:1234}

func NewDecoder

func NewDecoder(r io.Reader, v Validator) *Decoder

NewDecoder creates an underlying Decoder with a given key and input reader

func (*Decoder) Decode

func (dec *Decoder) Decode(v interface{}) error

Decode consumes the next available token from the given reader and populates a given interface with the matching values in the the token. The signature of the given token is verified and will return an error if a bad signature is found. In addition if the jwt is using an unimplemented algorithm an error will be returned as well.

type ESValidator

type ESValidator struct {
	PrivateKey *ecdsa.PrivateKey
	PublicKey  *ecdsa.PublicKey
	// contains filtered or unexported fields
}

An ESValidator implments the validator interface and provides a signing and Validation tool for Elliptic curve signed tokens

func NewESValidator

func NewESValidator(algorithm Algorithm) (v ESValidator, err error)

NewESValidator instantiates a new instance of a parameterized Elliptic validator

type Encoder

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

An Encoder is a centeralized writer and key used to take a given payload and produce a jwt token.

Example
payload := &struct {
	Payload
	Admin  bool `json:"admin"`
	UserID int  `json:"user_id"`
}{
	Payload: Payload{Issuer: "Ben Campbell"},
	Admin:   true,
	UserID:  1234,
}
tokenBuffer := bytes.NewBuffer(nil)

v := NewHSValidator(HS256)
v.Key = []byte("bogokey")

err := NewEncoder(tokenBuffer, v).Encode(payload)

if err != nil {
	panic(err)
}

fmt.Println(tokenBuffer.String())
Output:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJCZW4gQ2FtcGJlbGwiLCJhZG1pbiI6dHJ1ZSwidXNlcl9pZCI6MTIzNH0.r4W8qDl8i8cUcRUxtA3hM0SZsLScHiBgBKZc_n_GrXI

func NewEncoder

func NewEncoder(w io.Writer, v Validator) *Encoder

NewEncoder creates an underlying Encoder with a given key and output writer

func (*Encoder) Encode

func (enc *Encoder) Encode(v interface{}) error

Encode takes a given payload and algorithm and composes a new signed jwt in the underlying writer. This will return an error in the event that the given payload cannot be encoded to JSON.

type Payload

type Payload struct {
	Issuer         string     `json:"iss,omitempty"`
	Subject        string     `json:"sub,omitempty"`
	Audience       string     `json:"aud,omitempty"`
	ExpirationTime *time.Time `json:"exp,omitempty"`
	NotBefore      *time.Time `json:"nbf,omitempty"`
	IssuedAt       *time.Time `json:"iat,omitempty"`
	JWTId          string     `json:"jti,omitempty"`
	// contains filtered or unexported fields
}

A Payload in a jwt represents a set of claims for a given token.

type RSValidator

type RSValidator struct {
	PublicKey  *rsa.PublicKey
	PrivateKey *rsa.PrivateKey
	// contains filtered or unexported fields
}

A RSValidator implments the validator interface and allows the singing and verification of signatures with RSA PCSK1.5 algorithms.

func NewRSValidator

func NewRSValidator(algorithm Algorithm) (v RSValidator, err error)

NewRSValidator constructs a RSValidator

type Validator

type Validator interface {
	// contains filtered or unexported methods
}

A Validator describes a pair of algorithmic operations that can be performed on a give jwt.

Jump to

Keyboard shortcuts

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