jwt

package module
Version: v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2018 License: MIT Imports: 16 Imported by: 8

README

jwt (JSON Web Token for Go)

JWT Compatible

Build Status Build status GoDoc Sourcegraph

About

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

When it comes to JWT, there are lots of libraries available for Go. Still, I couldn't find one that was simple enough to use, so I decided to create this library in order to help whomever needs an easy solution for JWT.

The main difference between other libraries is ease of use. This library is pretty straightforward and has no external dependencies. If one is used to easy-to-use libraries, like Node's, perhaps it is the ideal library for them to use.

Also, it supports header and payload validators and all hashing algorithms (both signing and verifying).

Usage

Full documentation here.

Examples

Issue a JWT
// Set the options.
now := time.Now()
opt := &jwt.Options{
	JWTID:          "unique_id",
	Timestamp:      true,
	ExpirationTime: now.Add(24 * 30 * 12 * time.Hour),
	NotBefore:      now.Add(30 * time.Minute),
	Subject:        "123",
	Audience:       "admin",
	Issuer:         "auth_server",
	KeyID:          "my_key",
	Public:         map[string]interface{}{"foo": "bar", "myBool": true},
}

// Define a signer.
sig := jwt.HS256("my_53cr37")

// Issue a new token.
token, err := jwt.Sign(sig, opt)
if err != nil {
	// ...
}
log.Print(token)
Verify a JWT
now := time.Now()
sig := jwt.HS256("my_53cr37")
jot, err := jwt.Verify(sig)
if err != nil {
	// token is invalid
}
Validate a JWT
algValidator := jwt.AlgorithmValidator(jwt.MethodHS256)
expValidator := jwt.ExpirationTimeValidator(now)
audValidator := jwt.AudienceValidator("admin")
if err = jot.Validate(algValidator, expValidator, audValidator); err != nil {
	switch err {
	case jwt.ErrAlgorithmMismatch:
		// handle "alg" mismatch
	case jwt.ErrTokenExpired:
		// handle "exp" being expired
	}
	case jwt.ErrAudienceMismatch:
		// handle "aud" mismatch
}

Contribution

How to help:
  • Pull Requests
  • Issues
  • Opinions

Documentation

Overview

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

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/gbrlsnchs/jwt"
)

func main() {
	// Timestamp the exact moment this function runs
	// for validating purposes.
	now := time.Now()
	// Mock an HTTP request for showing off token extraction.
	w := httptest.NewRecorder()
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	// Build JWT from the incoming request.
	jot, err := jwt.FromRequest(r)

	if err != nil {
		// Handle malformed token...
	}

	if err = jot.Verify(jwt.HS256("secret")); err != nil {
		// Handle verification error...
	}

	// Define validators for validating the JWT. If desired, there
	// could be custom validators too, e.g. to validate public claims.
	algValidator := jwt.AlgorithmValidator(jwt.MethodHS256)
	audValidator := jwt.AudienceValidator("test")
	expValidator := jwt.ExpirationTimeValidator(now)

	if err = jot.Validate(algValidator, audValidator, expValidator); err != nil {
		switch err {
		case jwt.ErrAlgorithmMismatch:
			// Handle "alg" mismatch...

		case jwt.ErrAudienceMismatch:
			// Handle "aud" mismatch...

		case jwt.ErrTokenExpired:
			// Handle "exp" being expired...
		}
	}

	// "Sign" issues a raw string, but if desired, one could also
	// use "FromString" method to have a JWT object.
	token, err := jwt.Sign(jwt.HS256("secret"), &jwt.Options{Timestamp: true})

	if err != nil {
		// ...
	}

	auth := fmt.Sprintf("Bearer %s", token)

	w.Header().Set("Authorization", auth)
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(token))
}
Output:

Index

Examples

Constants

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

)

Variables

View Source
var (
	ErrNoECDSAPrivKey = errors.New("jwt.(Signer).Sign: ECDSA private key is nil")
	ErrNoECDSAPubKey  = errors.New("jwt.(Signer).Sign: ECDSA public key is nil")
	ErrECSDAInvalid   = errors.New("jwt.(Signer).Verify: ECDSA validation failed")
	ErrECDSASigLen    = errors.New("jwt.(Signer).Verify: ECDSA signature has unexpected size")
)
View Source
var (
	ErrNoHMACKey   = errors.New("jwt.(Signer).Sign: HMAC key is empty")
	ErrHMACInvalid = errors.New("jwt.(Signer).Verify: HMAC validation failed")
)
View Source
var (
	// ErrEmptyAuthorization indicates that the "Authorization" header
	// doesn't have a token and, thus, extracting a token is impossible.
	ErrEmptyAuthorization = errors.New("jwt: no token could be extracted from header")
	// ErrMalformedToken indicates a token doesn't have
	// a valid format, as per the RFC 7519, section 7.2.
	ErrMalformedToken = errors.New("jwt: malformed token")
	// ErrNilCtxKey indicates that no context key is set for retrieving
	// JWTs from context objects. This error is resolved if a key is set.
	ErrNilCtxKey = errors.New("jwt: JWT context key is a nil value")
	// ErrNilCtxValue indicates the context value is nil.
	// This mitigates possible nil pointer reference problems
	// and avoids tiring and unnecessary JWT pointer checking.
	ErrNilCtxValue = errors.New("jwt: context value is nil")
	// ErrCtxAssertion indicates a JWT could not be extracted from a context object
	// because the value it holds can not be asserted to a JWT pointer.
	ErrCtxAssertion = errors.New("jwt: unable to assert context value into JWT pointer")
)
View Source
var (
	ErrNoRSAPrivKey = errors.New("jwt.(Signer).Sign: RSA private key is nil")
	ErrNoRSAPubKey  = errors.New("jwt.(Signer).Verify: RSA public key is nil")
)
View Source
var (
	ErrAlgorithmMismatch = errors.New("jwt: Algorithm mismatch")
	ErrAudienceMismatch  = errors.New("jwt: Audience mismatch")
	ErrTokenExpired      = errors.New("jwt: Token expired")
	ErrTokenFromFuture   = errors.New("jwt: Token issued at the future")
	ErrTokenTooYoung     = errors.New("jwt: Token is not valid yet")
	ErrIssuerMismatch    = errors.New("jwt: Issuer mismatch")
	ErrJWTIDMismatch     = errors.New("jwt: JWTID mismatch")
	ErrSubjectMismatch   = errors.New("jwt: Subject mismatch")
)
View Source
var ErrNoSigner = errors.New("jwt.Sign: signer is nil")

Functions

func Sign

func Sign(s Signer, opt *Options) (string, error)

Sign builds a full JWT and signs its last part.

Example
package main

import (
	"fmt"
	"time"

	"github.com/gbrlsnchs/jwt"
)

func main() {
	nextYear := time.Now().Add(24 * 30 * 12 * time.Hour)
	token, err := jwt.Sign(jwt.HS256("secret"), &jwt.Options{ExpirationTime: nextYear})

	if err != nil {
		// ...
	}

	fmt.Println(token)
}
Output:

Types

type JWT

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

JWT is a JSON Web Token.

func FromContext added in v0.5.0

func FromContext(ctx context.Context, key interface{}) (*JWT, error)

FromContext extracts a JWT object from a given context.

Example
package main

import (
	"context"
	"fmt"

	"github.com/gbrlsnchs/jwt"
)

func main() {
	jot, err := jwt.FromString("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M")

	if err != nil {
		// Handle malformed token...
	}

	key := "JWT"
	ctx := context.WithValue(context.Background(), key, jot)
	jot, err = jwt.FromContext(ctx, key)

	if err != nil {
		// Handle JWT absence from context...
	}

	fmt.Println(jot)
}
Output:

func FromCookie added in v0.5.0

func FromCookie(c *http.Cookie) (*JWT, error)

FromCookie extracts a JWT object from a given cookie.

func FromRequest added in v0.3.0

func FromRequest(r *http.Request) (*JWT, error)

FromRequest builds a JWT from the token contained in the "Authorization" header.

func FromString added in v0.4.0

func FromString(s string) (*JWT, error)

FromString builds a JWT from a string representation of a JSON Web Token.

Example
package main

import (
	"fmt"

	"github.com/gbrlsnchs/jwt"
)

func main() {
	jot, err := jwt.FromString("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M")

	if err != nil {
		// Handle malformed token...
	}

	if err = jot.Verify(jwt.HS256("secret")); err != nil {
		// Handle verification error...
	}

	fmt.Println(jot)
}
Output:

func (*JWT) Algorithm added in v0.3.0

func (j *JWT) Algorithm() string

Algorithm returns the "alg" claim from the JWT's header.

func (*JWT) Audience added in v0.3.0

func (j *JWT) Audience() string

Audience returns the "aud" claim from the JWT's payload.

func (*JWT) Bytes added in v0.4.0

func (j *JWT) Bytes() []byte

Bytes returns a representation of the JWT as an array of bytes.

func (*JWT) ExpirationTime added in v0.3.0

func (j *JWT) ExpirationTime() time.Time

ExpirationTime returns the "exp" claim from the JWT's payload.

func (*JWT) ID added in v0.4.0

func (j *JWT) ID() string

ID returns the "jti" claim from the JWT's payload.

func (*JWT) IssuedAt added in v0.3.0

func (j *JWT) IssuedAt() time.Time

IssuedAt returns the "iat" claim from the JWT's payload.

func (*JWT) Issuer added in v0.3.0

func (j *JWT) Issuer() string

Issuer returns the "iss" claim from the JWT's payload.

func (*JWT) KeyID added in v0.3.0

func (j *JWT) KeyID() string

KeyID returns the "kid" claim from the JWT's header.

func (*JWT) NotBefore added in v0.3.0

func (j *JWT) NotBefore() time.Time

NotBefore returns the "nbf" claim from the JWT's payload.

func (*JWT) Public added in v0.3.0

func (j *JWT) Public() map[string]interface{}

Public returns all public claims set.

func (*JWT) String added in v0.4.0

func (j *JWT) String() string

func (*JWT) Subject added in v0.3.0

func (j *JWT) Subject() string

Subject returns the "sub" claim from the JWT's payload.

func (*JWT) Validate added in v0.4.0

func (j *JWT) Validate(vfuncs ...ValidatorFunc) error

Validate iterates over custom validator functions to validate the JWT.

func (*JWT) Verify added in v0.4.0

func (j *JWT) Verify(s Signer) error

Verify verifies the Token's signature.

type Options added in v0.3.0

type Options struct {
	JWTID          string                 // JWTID is the "jti" claim.
	Timestamp      bool                   // Timestamp defines whether the JWT has the "iat" (issued at) claim set.
	ExpirationTime time.Time              // ExpirationTime is the "exp" claim.
	NotBefore      time.Time              // NotBefore is the "nbf" claim.
	Subject        string                 // Subject is the "sub" claim.
	Audience       string                 // Audience is the "aud" claim.
	Issuer         string                 // Issuer is the "iss" claim.
	KeyID          string                 // KeyID is the "kid" header claim.
	Public         map[string]interface{} // Public is a collection of public claims that are included to the JWT's payload.
}

Options is a set of options that defines claims that are included in a token.

type Signer added in v0.3.0

type Signer interface {
	Sign(msg []byte) ([]byte, error)
	String() string
	Verify(msg, sig []byte) error
}

func ES256 added in v0.3.0

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

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

func ES384 added in v0.3.0

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

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

func ES512 added in v0.3.0

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

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

func HS256 added in v0.3.0

func HS256(key string) Signer

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

func HS384 added in v0.3.0

func HS384(key string) Signer

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

func HS512 added in v0.3.0

func HS512(key string) Signer

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

func None added in v0.4.0

func None() Signer

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

func RS256 added in v0.3.0

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

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

func RS384 added in v0.3.0

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

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

func RS512 added in v0.3.0

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

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

type ValidatorFunc added in v0.4.0

type ValidatorFunc func(jot *JWT) error

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

func AlgorithmValidator added in v0.4.0

func AlgorithmValidator(alg string) ValidatorFunc

AlgorithmValidator validates the "alg" claim.

func AudienceValidator added in v0.4.0

func AudienceValidator(aud string) ValidatorFunc

AudienceValidator validates the "aud" claim.

func ExpirationTimeValidator added in v0.4.0

func ExpirationTimeValidator(now time.Time) ValidatorFunc

ExpirationTimeValidator validates the "exp" claim.

func IDValidator added in v0.4.0

func IDValidator(jti string) ValidatorFunc

IDValidator validates the "jti" claim.

func IssuedAtValidator added in v0.4.0

func IssuedAtValidator(now time.Time) ValidatorFunc

IssuedAtValidator validates the "iat" claim.

func IssuerValidator added in v0.4.0

func IssuerValidator(iss string) ValidatorFunc

IssuerValidator validates the "iss" claim.

func NotBeforeValidator added in v0.4.0

func NotBeforeValidator(now time.Time) ValidatorFunc

NotBeforeValidator validates the "nbf" claim.

func SubjectValidator added in v0.4.0

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