Back to godoc.org
github.com/gbrlsnchs/jwt

Package jwt

v1.1.0
Latest Go to latest

The latest major version is v3.

Published: Aug 22, 2018 | License: MIT | Module: github.com/gbrlsnchs/jwt

Overview

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

Example

Code:

package main

import (
	"fmt"
	"github.com/gbrlsnchs/jwt"
	"net/http"
	"net/http/httptest"
	"time"
)

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))
}

Index

Examples

Constants

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

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")
)
var (
	ErrNoHMACKey   = errors.New("jwt.(Signer).Sign: HMAC key is empty")
	ErrHMACInvalid = errors.New("jwt.(Signer).Verify: HMAC validation failed")
)
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")
)
var (
	ErrNoRSAPrivKey = errors.New("jwt.(Signer).Sign: RSA private key is nil")
	ErrNoRSAPubKey  = errors.New("jwt.(Signer).Verify: RSA public key is nil")
)
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")
)
var ErrNoSigner = errors.New("jwt.Sign: signer is nil")

func Sign

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

Sign builds a full JWT and signs its last part.

Example

Code:

package main

import (
	"fmt"
	"github.com/gbrlsnchs/jwt"
	"time"
)

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)
}

type JWT

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

JWT is a JSON Web Token.

func FromContext

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

FromContext extracts a JWT object from a given context.

Example

Code:

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)
}

func FromCookie

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

FromCookie extracts a JWT object from a given cookie.

func FromRequest

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

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

func FromString

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

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

Example

Code:

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)
}

func (*JWT) Algorithm

func (j *JWT) Algorithm() string

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

func (*JWT) Audience

func (j *JWT) Audience() string

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

func (*JWT) Bytes

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

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

func (*JWT) ExpirationTime

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

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

func (*JWT) ID

func (j *JWT) ID() string

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

func (*JWT) IssuedAt

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

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

func (*JWT) Issuer

func (j *JWT) Issuer() string

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

func (*JWT) KeyID

func (j *JWT) KeyID() string

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

func (*JWT) NotBefore

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

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

func (*JWT) Public

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

Public returns all public claims set.

func (*JWT) String

func (j *JWT) String() string

func (*JWT) Subject

func (j *JWT) Subject() string

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

func (*JWT) Validate

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

Validate iterates over custom validator functions to validate the JWT.

func (*JWT) Verify

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

Verify verifies the Token's signature.

type Options

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

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

func ES256

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

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

func ES384

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

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

func ES512

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

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

func HS256

func HS256(key string) Signer

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

func HS384

func HS384(key string) Signer

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

func HS512

func HS512(key string) Signer

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

func None

func None() Signer

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

func RS256

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

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

func RS384

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

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

func RS512

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

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

type ValidatorFunc

type ValidatorFunc func(jot *JWT) error

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

func AlgorithmValidator

func AlgorithmValidator(alg string) ValidatorFunc

AlgorithmValidator validates the "alg" claim.

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.

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier