jwt

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2018 License: MIT Imports: 14 Imported by: 9

README

jwt (JSON Web Token for Go)

JWT compatible

Build status Build status Sourcegraph GoDoc Minimal version

About

This package is a JWT signer, verifier and validator for Go (or Golang).

Although there are many JWT packages out there for Go, many lack support for some signing, verifying or validation methods and, when they don't, they're overcomplicated. This package tries to mimic the ease of use from Node JWT library's API while following the Effective Go guidelines.

Support for JWE isn't provided. Instead, JWS is used, narrowed down to the JWT specification.

Installing
Go 1.10

vgo get -u github.com/gbrlsnchs/jwt/v2

Go 1.11 or after

go get -u github.com/gbrlsnchs/jwt/v2

Importing
import (
	// ...

	github.com/gbrlsnchs/jwt/v2
)

Usage

Full documentation here.

Signing a simple JWT
// Timestamp the beginning.
now := time.Now()
// Define a signer.
hs256 := jwt.NewHS256("secret")
jot := &jwt.JWT{
	Issuer:         "gbrlsnchs",
	Subject:        "someone",
	Audience:       "gophers",
	ExpirationTime: now.Add(24 * 30 * 12 * time.Hour).Unix(),
	NotBefore:      now.Add(30 * time.Minute).Unix(),
	IssuedAt:       now.Unix(),
	ID:             "foobar",
}
jot.SetAlgorithm(hs256)
jot.SetKeyID("kid")
payload, err := jwt.Marshal(jot)
if err != nil {
	// handle error
}
token, err := hs256.Sign(payload)
if err != nil {
	// handle error
}
log.Printf("token = %s", token)
Signing a JWT with public claims
First, create a custom type and embed a JWT pointer in it
type Token struct {
	*jwt.JWT
	IsLoggedIn  bool   `json:"isLoggedIn"`
	CustomField string `json:"customField,omitempty"`
}
Now initialize, marshal and sign it
// Timestamp the beginning.
now := time.Now()
// Define a signer.
hs256 := jwt.NewHS256("secret")
jot := &Token{
	JWT: &jwt.JWT{
		Issuer:         "gbrlsnchs",
		Subject:        "someone",
		Audience:       "gophers",
		ExpirationTime: now.Add(24 * 30 * 12 * time.Hour).Unix(),
		NotBefore:      now.Add(30 * time.Minute).Unix(),
		IssuedAt:       now.Unix(),
		ID:             "foobar",
	},
	IsLoggedIn:  true,
	CustomField: "myCustomField",
}
jot.SetAlgorithm(hs256)
jot.SetKeyID("kid")
payload, err := jwt.Marshal(jot)
if err != nil {
	// handle error
}
token, err := hs256.Sign(payload)
if err != nil {
	// handle error
}
log.Printf("token = %s", token)
Verifying and validating a JWT
// Timestamp the beginning.
now := time.Now()
// Define a signer.
hs256 := jwt.NewHS256("secret")
// This is a mocked token for demonstration purposes only.
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.lZ1zDoGNAv3u-OclJtnoQKejE8_viHlMtGlAxE8AE0Q"

// First, extract the payload and signature.
// This enables unmarshaling the JWT first and
// verifying it later or vice versa.
payload, sig, err := jwt.Parse(token)
if err != nil {
	// handle error
}
var jot Token
if err = jwt.Unmarshal(payload, &jot); err != nil {
	// handle error
}
if err = hs256.Verify(payload, sig); err != nil {
	// handle error
}

// Validate fields.
iatValidator := jwt.IssuedAtValidator(now)
expValidator := jwt.ExpirationTimeValidator(now)
audValidator := jwt.AudienceValidator("admin")
if err = jot.Validate(algValidator, expValidator, audValidator); err != nil {
	switch err {
	case jwt.ErrIatValidation:
		// handle "iat" validation error
	case jwt.ErrExpValidation:
		// handle "exp" validation error
	case jwt.ErrAudValidation:
		// handle "aud" validation error
	}
}

Contributing

How to help

Documentation

Overview

Package jwt is a JSON Web Token signer, verifier and validator.

Index

Constants

View Source
const (
	// MethodHS256 is the method name for HMAC and SHA-256.
	MethodHS256 = "HS256"
	// MethodHS384 is the method name for HMAC and SHA-384.
	MethodHS384 = "HS384"
	// MethodHS512 is the method name for HMAC and SHA-512.
	MethodHS512 = "HS512"
	// MethodRS256 is the method name for RSA and SHA-256.
	MethodRS256 = "RS256"
	// MethodRS384 is the method name for RSA and SHA-384.
	MethodRS384 = "RS384"
	// MethodRS512 is the method name for RSA and SHA-512.
	MethodRS512 = "RS512"
	// MethodES256 is the method name for ECDSA and SHA-256.
	MethodES256 = "ES256"
	// MethodES384 is the method name for ECDSA and SHA-384.
	MethodES384 = "ES384"
	// MethodES512 is the method name for ECDSA and SHA-512.
	MethodES512 = "ES512"
	// MethodNone is the method name for an unsecured JWT.
	MethodNone = "none"
)

Variables

View Source
var (
	// ErrECDSANilPrivKey is the error for trying to sign a JWT with a nil private key.
	ErrECDSANilPrivKey = errors.New("jwt: ECDSA private key is nil")
	// ErrECDSANilPubKey is the error for trying to verify a JWT with a nil public key.
	ErrECDSANilPubKey = errors.New("jwt: ECDSA public key is nil")
	// ErrECDSAVerification is the error for an invalid signature.
	ErrECDSAVerification = errors.New("jwt: ECDSA verification failed")
)
View Source
var (
	// ErrNoHMACKey is the error for trying to sign or verify a JWT with an empty key.
	ErrNoHMACKey = errors.New("jwt: HMAC key is empty")
	// ErrHMACVerification is the error for an invalid signature.
	ErrHMACVerification = errors.New("jwt: HMAC verification failed")
)
View Source
var (
	// ErrRSANilPrivKey is the error for trying to sign a JWT with a nil private key.
	ErrRSANilPrivKey = errors.New("jwt: RSA private key is nil")
	// ErrRSANilPubKey is the error for trying to verify a JWT with a nil public key.
	ErrRSANilPubKey = errors.New("jwt: RSA public key is nil")
)
View Source
var (
	// ErrAudValidation is the error for an invalid "aud" claim.
	ErrAudValidation = errors.New("jwt: aud claim is invalid")
	// ErrExpValidation is the error for an invalid "exp" claim.
	ErrExpValidation = errors.New("jwt: exp claim is invalid")
	// ErrIatValidation is the error for an invalid "iat" claim.
	ErrIatValidation = errors.New("jwt: iat claim is invalid")
	// ErrIssValidation is the error for an invalid "iss" claim.
	ErrIssValidation = errors.New("jwt: iss claim is invalid")
	// ErrJtiValidation is the error for an invalid "jti" claim.
	ErrJtiValidation = errors.New("jwt: jti claim is invalid")
	// ErrNbfValidation is the error for an invalid "nbf" claim.
	ErrNbfValidation = errors.New("jwt: nbf claim is invalid")
	// ErrSubValidation is the error for an invalid "sub" claim.
	ErrSubValidation = errors.New("jwt: sub claim is invalid")
)
View Source
var (
	// ErrMalformed indicates a token doesn't have
	// a valid format, as per the RFC 7519.
	ErrMalformed = errors.New("jwt: malformed token")
)

Functions

func Marshal

func Marshal(v interface{}) ([]byte, error)

Marshal marshals a struct or a pointer to a struct according to RFC 7519 and returns a JWT payload encoded to Base64.

func Parse

func Parse(token string) ([]byte, []byte, error)

Parse returns both the payload and the signature encoded to Base64 or an error if token is invalid.

func ParseBytes

func ParseBytes(token []byte) ([]byte, []byte, error)

ParseBytes does the same parsing as Parse but accepts a byte slice instead.

func Unmarshal

func Unmarshal(b []byte, v interface{}) error

Unmarshal unmarshals a token according to RFC 7519 and assigns a JWT to an interface.

Types

type JWT

type JWT struct {
	Issuer         string `json:"iss,omitempty"`
	Subject        string `json:"sub,omitempty"`
	Audience       string `json:"aud,omitempty"`
	ExpirationTime int64  `json:"exp,omitempty"`
	NotBefore      int64  `json:"nbf,omitempty"`
	IssuedAt       int64  `json:"iat,omitempty"`
	ID             string `json:"jti,omitempty"`
	// contains filtered or unexported fields
}

JWT is a JSON Web Token as per the RFC 7519.

Fields are ordered according to the RFC 7519 order.

func (*JWT) Algorithm

func (jot *JWT) Algorithm() string

Algorithm returns the JWT's header's algorithm.

func (*JWT) ContentType

func (jot *JWT) ContentType() string

ContentType returns the JWT's header's content type.

func (*JWT) KeyID

func (jot *JWT) KeyID() string

KeyID returns the JWT's header's key ID.

func (*JWT) SetAlgorithm

func (jot *JWT) SetAlgorithm(s Signer)

SetAlgorithm sets the algorithm a JWT uses to be signed.

func (*JWT) SetContentType

func (jot *JWT) SetContentType(cty string)

SetContentType sets the JWT's header's content type.

This is useful if a type implements the Marshaler and the Unmarshaler types in order to use JWE instead of JWS for signing and verifying.

func (*JWT) SetKeyID

func (jot *JWT) SetKeyID(kid string)

SetKeyID sets the key ID assigned to a JWT.

func (*JWT) Type

func (jot *JWT) Type() string

Type returns the JWT's header's type.

func (*JWT) Validate

func (jot *JWT) Validate(validators ...ValidatorFunc) error

Validate validates claims and header fields.

type Marshaler

type Marshaler interface {
	MarshalJWT() ([]byte, error)
}

Marshaler is the interface by types that can marshal a JWT description of themselves.

type Signer

type Signer interface {
	// Sign signs a JWT payload and returns a complete JWT (payload + signature).
	Sign([]byte) ([]byte, error)
	// Verify verifies a payload and a signature.
	// It returns an error with details of why verification failed or a nil one if verification is OK.
	Verify([]byte, []byte) error
	String() string // prints a specific text used in the "alg" field
}

Signer is a signing method capable of both signing and verifying a JWT.

func NewES256

func NewES256(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer

NewES256 creates a signing method using ECDSA and SHA-256.

func NewES384

func NewES384(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer

NewES384 creates a signing method using ECDSA and SHA-384.

func NewES512

func NewES512(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer

NewES512 creates a signing method using ECDSA and SHA-512.

func NewHS256

func NewHS256(key string) Signer

NewHS256 creates a signing method using HMAC and SHA-256.

func NewHS384

func NewHS384(key string) Signer

NewHS384 creates a signing method using HMAC and SHA-384.

func NewHS512

func NewHS512(key string) Signer

NewHS512 creates a signing method using HMAC and SHA-512.

func NewRS256

func NewRS256(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer

NewRS256 creates a signing method using RSA and SHA-256.

func NewRS384

func NewRS384(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer

NewRS384 creates a signing method using RSA and SHA-384.

func NewRS512

func NewRS512(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer

NewRS512 creates a signing method using RSA and SHA-512.

func None

func None() Signer

None returns a Signer that bypasses signing and validating, thus implementing the "none" method.

type Unmarshaler

type Unmarshaler interface {
	UnmarshalJWT([]byte) error
}

Unmarshaler is the interface inmplemented by types that can unmarshal a JWT description of themselves.

type ValidatorFunc

type ValidatorFunc func(jot *JWT) error

ValidatorFunc is a function for running extra validators when parsing a JWT string.

func AudienceValidator

func AudienceValidator(aud string) ValidatorFunc

AudienceValidator validates the "aud" claim.

func ExpirationTimeValidator

func ExpirationTimeValidator(now time.Time) ValidatorFunc

ExpirationTimeValidator validates the "exp" claim.

func IDValidator

func IDValidator(jti string) ValidatorFunc

IDValidator validates the "jti" claim.

func IssuedAtValidator

func IssuedAtValidator(now time.Time) ValidatorFunc

IssuedAtValidator validates the "iat" claim.

func IssuerValidator

func IssuerValidator(iss string) ValidatorFunc

IssuerValidator validates the "iss" claim.

func NotBeforeValidator

func NotBeforeValidator(now time.Time) ValidatorFunc

NotBeforeValidator validates the "nbf" claim.

func SubjectValidator

func SubjectValidator(sub string) ValidatorFunc

SubjectValidator validates the "sub" claim.

Jump to

Keyboard shortcuts

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