jwt

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2018 License: CC0-1.0 Imports: 20 Imported by: 0

README

API Documentation Build Status Test Coverage

A JSON Web Token (JWT) library for the Go programming language.

The API enforces secure use by design. Unsigned tokens are rejected and there is no support for encryption—use wire encryption instead. With about 700 lines of code and no third party dependencies, the implementation maintains full unit test coverage.

This is free and unencumbered software released into the public domain.

Get Started

The package comes with functions to verify [ECDSACheck, HMACCheck, RSACheck] and issue [ECDSASign, HMACSign, RSASign] claims.

For server side security an http.Handler based setup can be used as well. The following example enforces the subject, formatted name and roles to be present as a valid JWT in all requests towards the MyAPI handler.

// configuration demo
http.DefaultServeMux.Handle("/api/v1", &jwt.Handler{
	Target: MyAPI, // the protected service multiplexer
	RSAKey: JWTPublicKey,

	// map some claims to HTTP headers
	HeaderBinding: map[string]string{
		"sub": "X-Verified-User", // registered [standard] claim
		"fn":  "X-Verified-Name", // private [custom] claim
	},

	// customise further with RBAC
	Func: func(w http.ResponseWriter, req *http.Request, claims *jwt.Claims) (pass bool) {
		log.Printf("got a valid JWT %q for %q", claims.ID, claims.Audience)

		// map role enumeration
		s, ok := claims.String("roles")
		if !ok {
			http.Error(w, "jwt: want roles claim as a string", http.StatusForbidden)
			return false
		}
		req.Header["X-Verified-Roles"] = strings.Fields(s)

		return true
	},
})

When all applicable JWT claims are mapped to HTTP request headers, then the service logic can stay free of verification code plus easier unit testing.

// Greeting is a standard HTTP handler fuction.
func Greeting(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "Hello %s!\nYou are authorized as %s.\n",
		req.Header.Get("X-Verified-Name"), req.Header.Get("X-Verified-User"))
}

Optionally one can use the claims object in the service handlers as shown in the “direct” example.

Performance on a Mac Pro (late 2013)

BenchmarkECDSASign/ES256-12         	   50000	     38114 ns/op
BenchmarkECDSASign/ES384-12         	     300	   4279447 ns/op
BenchmarkECDSASign/ES512-12         	     200	   8064569 ns/op
BenchmarkECDSACheck/ES256-12        	   10000	    105350 ns/op
BenchmarkECDSACheck/ES384-12        	     200	   8331596 ns/op
BenchmarkECDSACheck/ES512-12        	     100	  16024017 ns/op
BenchmarkHMACSign/HS256-12          	  500000	      3498 ns/op
BenchmarkHMACSign/HS384-12          	  300000	      4071 ns/op
BenchmarkHMACSign/HS512-12          	  300000	      4144 ns/op
BenchmarkHMACCheck/HS256-12         	  200000	      6834 ns/op
BenchmarkHMACCheck/HS384-12         	  200000	      7543 ns/op
BenchmarkHMACCheck/HS512-12         	  200000	      7622 ns/op
BenchmarkRSASign/1024-bit-12        	    3000	    424131 ns/op
BenchmarkRSASign/2048-bit-12        	    1000	   2102947 ns/op
BenchmarkRSASign/4096-bit-12        	     100	  12877484 ns/op
BenchmarkRSACheck/1024-bit-12       	   50000	     32982 ns/op
BenchmarkRSACheck/2048-bit-12       	   20000	     73431 ns/op
BenchmarkRSACheck/4096-bit-12       	   10000	    201450 ns/op

JWT.io

Documentation

Overview

Package jwt implements "JSON Web Token (JWT)" RFC 7519. Signatures only; no unsecured nor encrypted tokens.

Example

Happy path for standard HTTP handler fuction security.

package main

import (
	"crypto/rsa"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"

	"github.com/pascaldekloe/jwt"
)

var someRSAKey *rsa.PrivateKey

func main() {
	// run secured service
	srv := httptest.NewTLSServer(&jwt.Handler{
		Target: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			fmt.Fprintf(w, "Hello %s!\n", req.Header.Get("X-Verified-Name"))
			fmt.Fprintf(w, "You are authorized as %s.\n", req.Header.Get("X-Verified-User"))
		}),
		RSAKey: &someRSAKey.PublicKey,
		HeaderBinding: map[string]string{
			"sub": "X-Verified-User", // registered [standard] claim name
			"fn":  "X-Verified-Name", // private [custom] claim name
		},
	})
	defer srv.Close()

	// build request with claims
	req, _ := http.NewRequest("GET", srv.URL, nil)
	var claims jwt.Claims
	claims.Subject = "lakane"
	claims.Set = map[string]interface{}{
		"fn": "Lana Anthony Kane",
	}
	if err := claims.RSASignHeader(req, jwt.RS512, someRSAKey); err != nil {
		fmt.Println("sign error:", err)
	}

	// call service
	resp, _ := srv.Client().Do(req)
	fmt.Println("HTTP", resp.Status)
	io.Copy(os.Stdout, resp.Body)

}
Output:

HTTP 200 OK
Hello Lana Anthony Kane!
You are authorized as lakane.
Example (Extend)

Use custom algorithm.

package main

import (
	"crypto"
	_ "crypto/sha1" // must link into binary
	"fmt"

	"github.com/pascaldekloe/jwt"
)

// HS1 is a SHA1 extension.
const HS1 = "HS1"

func init() {
	// static registration
	jwt.HMACAlgs[HS1] = crypto.SHA1
}

// Use custom algorithm.
func main() {
	c := new(jwt.Claims)
	c.ID = "Me Too!"

	// issue
	token, err := c.HMACSign(HS1, []byte("guest"))
	if err != nil {
		fmt.Println("sign error:", err)
	}
	fmt.Printf("token: %s\n", token)

	// verify
	got, err := jwt.HMACCheck(token, []byte("guest"))
	if err != nil {
		fmt.Println("check error:", err)
	}
	fmt.Printf("JSON: %s\n", got.Raw)

}
Output:

token: eyJhbGciOiJIUzEifQ.eyJqdGkiOiJNZSBUb28hIn0.hHye7VnslIM4jO-MoBfggMe8MUQ
JSON: {"jti":"Me Too!"}
Example (NoneAlg)

Reject the "none" algorithm with ErrUnsecured.

_, err := HMACCheck([]byte("eyJhbGciOiJub25lIn0.e30."), nil)
fmt.Println(err)
Output:

jwt: unsecured—no signature

Index

Examples

Constants

View Source
const (
	HS256 = "HS256" // HMAC using SHA-256
	HS384 = "HS384" // HMAC using SHA-384
	HS512 = "HS512" // HMAC using SHA-512
	RS256 = "RS256" // RSASSA-PKCS1-v1_5 using SHA-256
	RS384 = "RS384" // RSASSA-PKCS1-v1_5 using SHA-384
	RS512 = "RS512" // RSASSA-PKCS1-v1_5 using SHA-512
	ES256 = "ES256" // ECDSA using P-256 and SHA-256
	ES384 = "ES384" // ECDSA using P-384 and SHA-384
	ES512 = "ES512" // ECDSA using P-521 and SHA-512
)

Algorithm Identification Tokens

View Source
const MIMEType = "application/jwt"

MIMEType is the IANA registered media type.

View Source
const OAuthURN = "urn:ietf:params:oauth:token-type:jwt"

OAuthURN is the IANA registered OAuth URI.

Variables

View Source
var (
	// ECDSAAlgs is the ECDSA hash algorithm registration.
	ECDSAAlgs = map[string]crypto.Hash{
		ES256: crypto.SHA256,
		ES384: crypto.SHA384,
		ES512: crypto.SHA512,
	}

	// HMACAlgs is the HMAC hash algorithm registration.
	HMACAlgs = map[string]crypto.Hash{
		HS256: crypto.SHA256,
		HS384: crypto.SHA384,
		HS512: crypto.SHA512,
	}

	// RSAAlgs is the RSA hash algorithm registration.
	RSAAlgs = map[string]crypto.Hash{
		RS256: crypto.SHA256,
		RS384: crypto.SHA384,
		RS512: crypto.SHA512,
	}
)

When adding additional entries you also need to import the respective packages to link the hash function into the binary crypto.Hash.Available.

View Source
var ErrAlgUnk = errors.New("jwt: algorithm unknown")

ErrAlgUnk signals an unsupported "alg" value (for the respective method).

View Source
var ErrNoHeader = errors.New("jwt: no HTTP Authorization")

ErrNoHeader signals an HTTP request without Authorization.

View Source
var ErrSigMiss = errors.New("jwt: signature mismatch")

ErrSigMiss means the signature check failed.

View Source
var ErrUnsecured = errors.New("jwt: unsecured—no signature")

ErrUnsecured signals the "none" algorithm.

Functions

This section is empty.

Types

type Claims

type Claims struct {
	// Registered field values take precedence.
	Registered

	// Raw has the JSON payload. This field is read-only.
	Raw json.RawMessage

	// Set has the claims set mapped by name for non-standard usecases.
	// Use Registered fields when possible.
	Set map[string]interface{}
}

Claims is JWT payload representation.

Example (Precedence)

Duplicate Set entries are ignored (and overridden by Sync).

offset := time.Unix(1537622794, 0)
c := Claims{
	Registered: Registered{
		Issuer:    "a",
		Subject:   "b",
		Audience:  "c",
		Expires:   NewNumericTime(offset.Add(time.Minute)),
		NotBefore: NewNumericTime(offset.Add(-time.Second)),
		Issued:    NewNumericTime(offset),
		ID:        "d",
	},
	Set: map[string]interface{}{
		"sub": "x",
		"exp": NewNumericTime(time.Now()),
		"jti": "y",
	},
}

// typed lookups by name
for _, name := range []string{"iss", "sub", "aud", "exp", "nbf", "iat", "jti"} {
	if s, ok := c.String(name); ok {
		fmt.Printf("%q: %q\n", name, s)
	}
	if n, ok := c.Number(name); ok {
		fmt.Printf("%q: %0.f\n", name, n)
	}
}

if err := c.Sync(); err != nil {
	fmt.Println("synchronisation error:", err)
}
fmt.Printf("%s\n", c.Raw)
Output:

"iss": "a"
"sub": "b"
"aud": "c"
"exp": 1537622854
"nbf": 1537622793
"iat": 1537622794
"jti": "d"
{"aud":"c","exp":1537622854,"iat":1537622794,"iss":"a","jti":"d","nbf":1537622793,"sub":"b"}

func ECDSACheck added in v1.1.0

func ECDSACheck(token []byte, key *ecdsa.PublicKey) (*Claims, error)

ECDSACheck parses a JWT and returns the claims set if, and only if, the signature checks out. Note that this excludes unsecured JWTs ErrUnsecured. When the algorithm is not in ECDSAAlgs, then the error is ErrAlgUnk. See Valid to complete the verification.

func ECDSACheckHeader added in v1.1.0

func ECDSACheckHeader(r *http.Request, key *ecdsa.PublicKey) (*Claims, error)

ECDSACheckHeader applies ECDSACheck on a HTTP request. Specifically it looks for a bearer token in the Authorization header.

func HMACCheck

func HMACCheck(token, secret []byte) (*Claims, error)

HMACCheck parses a JWT and returns the claims set if, and only if, the signature checks out. Note that this excludes unsecured JWTs ErrUnsecured. When the algorithm is not in HMACAlgs, then the error is ErrAlgUnk. See Valid to complete the verification.

func HMACCheckHeader

func HMACCheckHeader(r *http.Request, secret []byte) (*Claims, error)

HMACCheckHeader applies HMACCheck on a HTTP request. Specifically it looks for a bearer token in the Authorization header.

func RSACheck

func RSACheck(token []byte, key *rsa.PublicKey) (*Claims, error)

RSACheck parses a JWT and returns the claims set if, and only if, the signature checks out. Note that this excludes unsecured JWTs ErrUnsecured. When the algorithm is not in RSAAlgs, then the error is ErrAlgUnk. See Valid to complete the verification.

func RSACheckHeader

func RSACheckHeader(r *http.Request, key *rsa.PublicKey) (*Claims, error)

RSACheckHeader applies RSACheck on a HTTP request. Specifically it looks for a bearer token in the Authorization header.

func (*Claims) ECDSASign added in v1.1.0

func (c *Claims) ECDSASign(alg string, key *ecdsa.PrivateKey) (token []byte, err error)

ECDSASign calls Sync and returns a new JWT. When the algorithm is not in ECDSAAlgs, then the error is ErrAlgUnk. The caller must use the correct key for the respective algorithm (P-256 for ES256, P-384 for ES384 and P-521 for ES512) or risk malformed token production.

func (*Claims) ECDSASignHeader added in v1.1.0

func (c *Claims) ECDSASignHeader(r *http.Request, alg string, key *ecdsa.PrivateKey) error

ECDSASignHeader applies ECDSASign on a HTTP request. Specifically it sets a bearer token in the Authorization header.

func (*Claims) HMACSign

func (c *Claims) HMACSign(alg string, secret []byte) (token []byte, err error)

HMACSign calls Sync and returns a new JWT. When the algorithm is not in HMACAlgs, then the error is ErrAlgUnk.

func (*Claims) HMACSignHeader

func (c *Claims) HMACSignHeader(r *http.Request, alg string, secret []byte) error

HMACSignHeader applies HMACSign on a HTTP request. Specifically it sets a bearer token in the Authorization header.

func (*Claims) Number

func (c *Claims) Number(name string) (value float64, ok bool)

Number returns the claim when present and if the representation is a JSON number.

func (*Claims) RSASign

func (c *Claims) RSASign(alg string, key *rsa.PrivateKey) (token []byte, err error)

RSASign calls Sync and returns a new JWT. When the algorithm is not in RSAAlgs, then the error is ErrAlgUnk.

func (*Claims) RSASignHeader

func (c *Claims) RSASignHeader(r *http.Request, alg string, key *rsa.PrivateKey) error

RSASignHeader applies RSASign on a HTTP request. Specifically it sets a bearer token in the Authorization header.

func (*Claims) String

func (c *Claims) String(name string) (value string, ok bool)

String returns the claim when present and if the representation is a JSON string.

func (*Claims) Sync

func (c *Claims) Sync() error

Sync updates the Raw field. When the Set field is not nil, then all non-zero Registered values are copied into the map.

func (*Claims) Valid

func (c *Claims) Valid(t time.Time) bool

Valid returns whether the claims set may be accepted for processing at the given moment in time.

type Handler

type Handler struct {
	// Target is the secured service.
	Target http.Handler

	// Secret is the HMAC key.
	Secret []byte
	// ECDSAKey applies ECDSAAlgs and disables HMACAlgs when set.
	ECDSAKey *ecdsa.PublicKey
	// RSAKey applies RSAAlgs and disables HMACAlgs when set.
	RSAKey *rsa.PublicKey
	// KeyRegister disables Secret, ECDSAKey and RSAKey when set.
	KeyRegister *KeyRegister

	// HeaderBinding maps JWT claim names to HTTP header names.
	// All requests passed to Target have these headers set. In
	// case of failure the request is rejected with status code
	// 401 (Unauthorized) and a description.
	HeaderBinding map[string]string

	// When not nil, then Func is called after the JWT validation
	// succeeds and before any header bindings. Target is skipped
	// [request drop] when the return is false.
	// This feature may be used to further customise requests or
	// as a filter or as an extended http.HandlerFunc.
	Func func(http.ResponseWriter, *http.Request, *Claims) (pass bool)
}

Handler protects an http.Handler with security enforcements. Requests are passed to Target only when the JWT checks out.

Example (Deny)

Standard compliant security out-of-the-box.

package main

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

	"github.com/pascaldekloe/jwt"
)

var someECKey *ecdsa.PrivateKey

func main() {
	h := &jwt.Handler{
		Target: http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
			panic("reached target handler")
		}),

		ECDSAKey: &someECKey.PublicKey,

		Func: func(w http.ResponseWriter, req *http.Request, claims *jwt.Claims) (pass bool) {
			panic("reached JWT-enhanced handler")
		},
	}

	req := httptest.NewRequest("GET", "/had-something-for-this", nil)
	doReq := func() {
		resp := httptest.NewRecorder()
		h.ServeHTTP(resp, req)
		fmt.Printf("HTTP %d %s\n", resp.Code, resp.Header().Get("WWW-Authenticate"))
	}

	// request with no authorization
	doReq()

	// request with disabled algorithm
	var c jwt.Claims
	if err := c.HMACSignHeader(req, jwt.HS512, []byte("guest")); err != nil {
		fmt.Println(err)
	}
	doReq()

	// request with expired token
	c.Expires = jwt.NewNumericTime(time.Now().Add(-time.Second))
	if err := c.ECDSASignHeader(req, jwt.ES512, someECKey); err != nil {
		fmt.Println(err)
	}
	doReq()

}
Output:

HTTP 401 Bearer
HTTP 401 Bearer error="invalid_token", error_description="jwt: algorithm unknown"
HTTP 401 Bearer error="invalid_token", error_description="jwt: time constraints exceeded"
Example (Direct)

Full access to the JWT claims.

package main

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

	"github.com/pascaldekloe/jwt"
)

func main() {
	h := &jwt.Handler{
		Target: nil,
		Secret: []byte("killarcherdie"),

		// use as http.HandlerFunc with JWT argument
		Func: func(w http.ResponseWriter, req *http.Request, claims *jwt.Claims) (pass bool) {
			if n, ok := claims.Number("deadline"); !ok {
				fmt.Fprintln(w, "you don't have a deadline")
			} else {
				t := jwt.NumericTime(n)
				fmt.Fprintln(w, "deadline at", t.String())
			}
			return // false stops processing
		},
	}

	req := httptest.NewRequest("GET", "/status", nil)
	req.Header.Set("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJkZWFkbGluZSI6NjcxNTAwNzk5fQ.yeUUNOj4-RvNp5Lt0d3lpS7MTgsS_Uk9XnsXJ3kVLhw")
	resp := httptest.NewRecorder()
	h.ServeHTTP(resp, req)
	fmt.Printf("HTTP %d: %s", resp.Code, resp.Body)

}
Output:

HTTP 200: deadline at 1991-04-12T23:59:59Z

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP honors the http.Handler interface.

type KeyRegister added in v1.1.0

type KeyRegister struct {
	ECDSAs  []*ecdsa.PublicKey // ECDSA credentials
	RSAs    []*rsa.PublicKey   // RSA credentials
	Secrets [][]byte           // HMAC credentials
}

KeyRegister contains a set of recognized credentials.

func (*KeyRegister) Check added in v1.1.0

func (r *KeyRegister) Check(token []byte) (*Claims, error)

Check parses a JWT and returns the claims set if, and only if, the signature checks out. Note that this excludes unsecured JWTs ErrUnsecured. See Claims.Valid to complete the verification.

func (*KeyRegister) CheckHeader added in v1.1.0

func (reg *KeyRegister) CheckHeader(r *http.Request) (*Claims, error)

CheckHeader applies KeyRegister.Check on a HTTP request. Specifically it looks for a bearer token in the Authorization header.

func (*KeyRegister) LoadPEM added in v1.1.0

func (r *KeyRegister) LoadPEM(data, password []byte) (n int, err error)

LoadPEM adds keys from PEM-encoded data and returns the count. PEM encryption is enforced for non-empty password values.

Example (Encrypted)

PEM with password protection.

package main

import (
	"fmt"

	"github.com/pascaldekloe/jwt"
)

func main() {
	const key = `-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,65789712555A3E9FECD1D5E235B97B0C

o0Dz8S6QjGVq59yQdlakuKkoO0jKDN0PDu2L05ZLXwBQSGdIbRXtAOBRCNEME0V1
IF9pM6uRU7tqFoVneNTHD3XySJG8AHrTPSKC3Xw31pjEolMfoNDBAu1bYR6XxM2X
oDu2UNVB9vd/3b4bwTH9q5ISWdCVhS/ky0lC9lHXman/F/7MsemiVVCQ4XTIi9CR
nitMxJuXvkNBMtsyv+inmFMegKU6dj1DU93B9JpsFRRvy3TCfj9kRjhKWEpyindo
yaZMH3EGOA3ALW5kWyr+XegyYznQbVdDlo/ikO9BAywBOx+DdRG4xYxRdxYt8/HH
qXwPAGQe2veMlR7Iq3GjwHLebyuVc+iHbC7feRmNBpAT1RR7J+RIGlDPOBMUpuDT
A8HbNzPkoXPGh9vMsREXtR5aPCaZISdcm8DTlNiZCPaX5VHL4SRJ5XjI2rnahaOE
rhCFy0mxqQaKnEI9kCWWFmhX/MqzzfiW3yg0qFIAVLDQZZMFJr3jMHIvkxPk09rP
nQIjMRBalFXmSiksx8UEhAzyriqiXwwgEI0gJVHcs3EIQGD5jNqvIYTX67/rqSF2
OXoYuq0MHrAJgEfDncXvZFFMuAS/5KMvzSXfWr5/L0ncCU9UykjdPrFvetG/7IXQ
BT1TX4pOeW15a6fg6KwSZ5KPrt3o8qtRfW4Ov49hPD2EhnCTMbkCRBbW8F13+9YF
xzvC4Vm1r/Oa4TTUbf5tVto7ua/lZvwnu5DIWn2zy5ZUPrtn22r1ymVui7Iuhl0b
SRcADdHh3NgrjDjalhLDB95ho5omG39l7qBKBTlBAYJhDuAk9rIk1FCfCB8upztt
-----END RSA PRIVATE KEY-----`

	var r jwt.KeyRegister
	n, err := r.LoadPEM([]byte(key), []byte("dangerzone"))
	if err != nil {
		fmt.Println("load error:", err)
	}
	fmt.Printf("got %d keys", n)
}
Output:

got 1 keys

type NumericTime

type NumericTime float64

NumericTime is a JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds.

func NewNumericTime

func NewNumericTime(t time.Time) *NumericTime

NewNumericTime returns the the corresponding representation with nil for the zero value.

func (*NumericTime) String

func (n *NumericTime) String() string

String returs the ISO representation.

func (*NumericTime) Time

func (n *NumericTime) Time() time.Time

Time returns the Go mapping with the zero value for nil.

type Registered

type Registered struct {
	// Issuer identifies the principal that issued the JWT.
	Issuer string `json:"iss,omitempty"`

	// Subject identifies the principal that is the subject of the JWT.
	Subject string `json:"sub,omitempty"`

	// Audience identifies the recipients that the JWT is intended for.
	Audience string `json:"aud,omitempty"`

	// Expires identifies the expiration time on or after which the JWT
	// must not be accepted for processing.
	Expires *NumericTime `json:"exp,omitempty"`

	// NotBefore identifies the time before which the JWT must not be
	// accepted for processing.
	NotBefore *NumericTime `json:"nbf,omitempty"`

	// Issued identifies the time at which the JWT was issued.
	Issued *NumericTime `json:"iat,omitempty"`

	// ID provides a unique identifier for the JWT.
	ID string `json:"jti,omitempty"`
}

Registered are the IANA registered "JSON Web Token Claims".

Jump to

Keyboard shortcuts

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