jwt

package module
v3.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2018 License: BSD-3-Clause Imports: 12 Imported by: 2

README

jwt - a simple JSON Web Token library written in Go

Usage

package main

import (
	"fmt"
	"git.giftfish.de/ston1th/jwt"
	"log"
	"time"
)

func main() {
	// create a new signing instance
	JWT, err := jwt.New(time.Hour, jwt.NewMemBlacklist(), nil)
	if err != nil {
		log.Fatal(err)
	}

	// create a new token
	t := jwt.NewToken(jwt.Claims{
		"username": "admin",
	}, nil)

	// sign the token
	err = JWT.Sign(t)
	if err != nil {
		log.Fatal(err)
	}

	// print the token string
	token := t.String()
	fmt.Println(token)

	// decode the token string
	newToken, err := jwt.DecodeToken(token)
	if err != nil {
		log.Fatal(err)
	}

	// verify the decoded token
	err = JWT.Verify(newToken)
	if err != nil {
		log.Fatal(err)
	}

	// add the token to the blacklist
	err = JWT.Invalidate(newToken)
	if err != nil {
		log.Fatal(err)
	}

	// try to verify the blacklisted token, it should fail
	err = JWT.Verify(newToken)
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Overview

Package jwt provides a easy to use JSON Web Token and blacklisting library

Index

Constants

View Source
const (
	HS256Name = "HS256"
	HS384Name = "HS384"
	HS512Name = "HS512"
)
View Source
const (
	// HTTPHeader is the default HTTP Authorization header name
	HTTPHeader = "Authorization"
	// DefaultExpiry is the default token expiration time
	DefaultExpiry = time.Hour * 12
	// KeySize is the secret key size
	KeySize = 64

	// Typ is the JWT type
	Typ = "JWT"
	// TypClaim is the typ claim name
	TypClaim = "typ"
	// AlgClaim is the alg claim name
	AlgClaim = "alg"
	// ExpClaim is the exp claim name
	ExpClaim = "exp"
	// NbfClaim is the nbf claim name
	NbfClaim = "nbf"
	// TokenSeparator is the tokens separator char
	TokenSeparator = "."
)

Variables

View Source
var (
	ErrNoJWT               = errors.New(jwtErr + "not a json web token")
	ErrEmptyToken          = errors.New(jwtErr + "token is empty")
	ErrUnsupportedAlg      = errors.New(jwtErr + "unsupported algorithm")
	ErrInvalid             = errors.New(jwtErr + "token validation failed")
	ErrBlacklisted         = errors.New(jwtErr + "token blacklisted")
	ErrBlacklistNotEnabled = errors.New(jwtErr + "blacklisting is not enabled")
	ErrNbf                 = errors.New(jwtErr + "token not valid yet")
	ErrExp                 = errors.New(jwtErr + "token expired")
	ErrMissingNbf          = errors.New(jwtErr + "missing nbf claim")
	ErrMissingExp          = errors.New(jwtErr + "missing exp claim")
	ErrMissingTokenParts   = errors.New(jwtErr + "missing token parts")
	ErrEmptySignature      = errors.New(jwtErr + "token signature is empty")
	ErrTokenIsNil          = errors.New(jwtErr + "token is nil")
	ErrInvalidKeySize      = errors.New(jwtErr + "invalid secret key size")
)
View Source
var DefaultSecretReader = rand.Reader

DefaultSecretReader is the default secret key generator

Functions

func NewExp

func NewExp(d time.Duration) int64

NewExp returns a new expiration date

func NewNbf

func NewNbf(t time.Time) int64

NewNbf returns a new 'not before' date

func Now

func Now() int64

Now returns the current time in UTC Unix format

Types

type Blacklist

type Blacklist interface {
	Add(string, int64) error
	Remove(string) error
	Check(string) bool
	Map() (BlacklistMap, error)
}

Blacklist is the blacklisting storage interface

type BlacklistMap

type BlacklistMap map[string]int64

BlacklistMap is the blacklist map structure

type Claims

type Claims map[string]interface{}

Claims is the claim type of the token The Claims map is not goroutine safe

func (Claims) Copy

func (c Claims) Copy() (n Claims)

Copy returns a new Claims map

func (Claims) Delete

func (c Claims) Delete(key string)

Delete removes the key from the claims map

func (Claims) Get

func (c Claims) Get(key string) (v interface{}, ok bool)

Get returns a value from the claims map

func (Claims) GetBool

func (c Claims) GetBool(key string) (b bool)

GetBool returns a bool from the claims map

func (Claims) GetFloat64

func (c Claims) GetFloat64(key string) (f float64)

GetFloat64 returns a float64 from the claims map

func (Claims) GetInt

func (c Claims) GetInt(key string) (i int)

GetInt returns an int from the claims map

func (Claims) GetInt64

func (c Claims) GetInt64(key string) (i int64)

GetInt64 returns an int64 from the claims map

func (Claims) GetString

func (c Claims) GetString(key string) (s string)

GetString returns a string from the claims map

func (Claims) Set

func (c Claims) Set(key string, v interface{})

Set sets the value of key in the claims map, if not nil

type HS256

type HS256 struct{}

HS256 implements the Hash interface with SHA256

func (HS256) Alg

func (HS256) Alg() string

Alg returns the algorithm name "HS256"

func (HS256) Hash

func (HS256) Hash() hash.Hash

Hash returns a new hash.Hash instance of the SHA256 algorithm

type HS384

type HS384 struct{}

HS384 implements the Hash interface with SHA384

func (HS384) Alg

func (HS384) Alg() string

Alg returns the algorithm name "HS384"

func (HS384) Hash

func (HS384) Hash() hash.Hash

Hash returns a new hash.Hash instance of the SHA384 algorithm

type HS512

type HS512 struct{}

HS512 implements the Hash interface with SHA512

func (HS512) Alg

func (HS512) Alg() string

Alg returns the algorithm name "HS512"

func (HS512) Hash

func (HS512) Hash() hash.Hash

Hash returns a new hash.Hash instance of the SHA512 algorithm

type Hash

type Hash interface {
	Hash() hash.Hash
	Alg() string
}

Hash is the hashsum interface for signing the jwt

func NewHS256

func NewHS256() Hash

NewHS256 returns a new HS256 instance

func NewHS384

func NewHS384() Hash

NewHS384 returns a new HS384 instance

func NewHS512

func NewHS512() Hash

NewHS512 returns a new HS512 instance

func ParseHash

func ParseHash(alg string) Hash

ParseHash returns the Hash type equal to the input string

type JWT

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

JWT represents the JSON Web Token signing and blacklisting infrastructure

func New

func New(expiry time.Duration, blacklist Blacklist, secret io.Reader) (*JWT, error)

New returns a new JWT object with the given expiry timeout. If the timeout is less or equal to zero the default expiry (12 hours) is used. The secret key size needs to be at least 64 bytes. If secret is nil the DefaultSecretReader is used. If blacklisting is enabled, the JWT object leaks a goroutine to garbage-collect expired blacklisted tokens. Call the Stop() method to exit the goroutine.

func (*JWT) Expiry

func (jwt *JWT) Expiry() time.Duration

Expiry returns the configured expiry

func (*JWT) Invalidate

func (jwt *JWT) Invalidate(t *Token) error

Invalidate checks if a token is already blacklisted If the token is not blacklisted, it will get blacklisted

func (*JWT) Sign

func (jwt *JWT) Sign(t *Token) (err error)

Sign will sign the provided token using the secret key If the 'exp' and 'nbf' claims do not exist, they will be written to the default values in UNIX format: 'exp': Now + expiry specified at New() or DefaultExpiry (UTC) 'nbf': Now (UTC)

func (*JWT) Stop

func (jwt *JWT) Stop() error

Stop will end the cleaner goroutine execution

func (*JWT) Verify

func (jwt *JWT) Verify(t *Token) error

Verify will verify the provided token using the secret key

type MemBlacklist

type MemBlacklist struct {
	// protects list
	sync.RWMutex
	// contains filtered or unexported fields
}

MemBlacklist implements the Blacklist interface

func NewMemBlacklist

func NewMemBlacklist() *MemBlacklist

NewMemBlacklist implements the Blacklist interface using an in-memory map

func (*MemBlacklist) Add

func (mb *MemBlacklist) Add(sig string, exp int64) error

Add adds a new token signature with expiration time to the blacklist

func (*MemBlacklist) Check

func (mb *MemBlacklist) Check(sig string) (ok bool)

Check returns true if a token signature is blacklisted and false otherwise

func (*MemBlacklist) Map

func (mb *MemBlacklist) Map() (list BlacklistMap, err error)

Map returns the blacklist in the form of a iterable map structure for cleanup

func (*MemBlacklist) Remove

func (mb *MemBlacklist) Remove(sig string) error

Remove deletes a token signature from the blacklist

type Token

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

Token represents a JWT token

func DecodeToken

func DecodeToken(token string) (t *Token, err error)

DecodeToken decodes a raw string token into a *Token object

func NewToken

func NewToken(claims Claims, hash Hash) *Token

NewToken returns a new *Token using the provided hash algorithm and claims If claims is nil, an empty map is used If hash is nil, HS256 is used

func (*Token) Data

func (t *Token) Data() string

Data returns the first two URLEncoded token fields

func (*Token) RawSig

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

RawSig returns the tokens raw signature

func (*Token) Sig

func (t *Token) Sig() string

Sig returns the tokens URLEncoded signature

func (*Token) String

func (t *Token) String() string

String returns the tokens encoded string

Jump to

Keyboard shortcuts

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