jwt

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2018 License: MIT Imports: 15 Imported by: 16

README

jwt (JSON Web Token for Go)

Build Status GoDoc

About

This package implements JWT signing and parsing for Go (or Golang).

It is simple and easy to use.

Usage

Full documentation here.

Example (from example_test.go)

package jwt_test

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

	"github.com/gbrlsnchs/jwt"
)

func Example() {
	now := time.Now()
	w := httptest.NewRecorder()
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	jot, err := jwt.FromRequest(r, jwt.HS256("secret"))

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

	if jot.Algorithm() != jwt.MethodHS256 ||
		!jot.ExpirationTime().IsZero() &&
			now.After(jot.ExpirationTime()) ||
		now.Before(jot.NotBefore()) {
		// Repudiate token.
	}

	token, err := jwt.Sign(jwt.HS256("secret"), &jwt.Options{Timestamp: true})

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

	w.Header().Set("Authorization", fmt.Sprintf("Bearer %s", token))
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(token))
}

func ExampleParse() {
	token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M"
	jot, err := jwt.Parse(jwt.HS256("secret"), token)

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

	fmt.Println(jot)
}

func ExampleSign() {
	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)
}

Contribution

How to help:
  • Pull Requests
  • Issues
  • Opinions

Documentation

Overview

Example
package main

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

	"github.com/gbrlsnchs/jwt"
)

func main() {
	now := time.Now()
	w := httptest.NewRecorder()
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	jot, err := jwt.FromRequest(r, jwt.HS256("secret"))

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

	if jot.Algorithm() != jwt.MethodHS256 ||
		!jot.ExpirationTime().IsZero() &&
			now.After(jot.ExpirationTime()) ||
		now.Before(jot.NotBefore()) {
		// Repudiate token.
	}

	token, err := jwt.Sign(jwt.HS256("secret"), &jwt.Options{Timestamp: true})

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

	w.Header().Set("Authorization", fmt.Sprintf("Bearer %s", token))
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(token))
}
Output:

Index

Examples

Constants

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

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 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 (
	// ErrInvalidSignature is returned when a token's
	// signature is invalidated by a signer.
	ErrInvalidSignature = errors.New("jwt.Parse: token has invalid signature")
	// ErrMalformedToken is returned when a token
	// doesn't contain a valid format of "header.payload.signature".
	ErrMalformedToken = errors.New("jwt.Parse: token is malformed")
)
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 ErrEmptyHeader = errors.New("jwt.FromRequest: no token could be extracted from header")

ErrEmptyHeader is returned when no token exists in the "Authorization" header.

View Source
var (
	ErrNoSigner = errors.New("jwt.Sign: signer is nil")
)

Functions

func Sign

func Sign(s Signer, opts *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 FromRequest added in v0.3.0

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

FromRequest extracts a token string from the "Authorization" header, which should contain the "Bearer <token>" pattern.

func Parse

func Parse(s Signer, token string) (*JWT, error)

Parse parses a string token using a specific signer and returns a JSON Web Token if all conditions are met for parsing it.

Example
package main

import (
	"fmt"

	"github.com/gbrlsnchs/jwt"
)

func main() {
	token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M"
	jot, err := jwt.Parse(jwt.HS256("secret"), token)

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

	fmt.Println(jot)
}
Output:

func (*JWT) Algorithm added in v0.3.0

func (j *JWT) Algorithm() string

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

func (*JWT) Audience added in v0.3.0

func (j *JWT) Audience() string

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

func (*JWT) ExpirationTime added in v0.3.0

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

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

func (*JWT) IssuedAt added in v0.3.0

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

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

func (*JWT) Issuer added in v0.3.0

func (j *JWT) Issuer() string

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

func (*JWT) KeyID added in v0.3.0

func (j *JWT) KeyID() string

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

func (*JWT) NotBefore added in v0.3.0

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

NotBefore returns the "nbf" claim from a 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) Subject added in v0.3.0

func (j *JWT) Subject() string

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

type Options added in v0.3.0

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

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 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.

Jump to

Keyboard shortcuts

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