jwt

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 3, 2020 License: MIT Imports: 19 Imported by: 423

README

jwt

JWT tokens

SYNOPSIS

package jwt_test

import (
  "bytes"
  "crypto/rand"
  "crypto/rsa"
  "encoding/json"
  "fmt"
  "time"

  "github.com/lestrrat-go/jwx/jwa"
  "github.com/lestrrat-go/jwx/jwt"
)

func ExampleSignAndParse() {
  privKey, err := rsa.GenerateKey(rand.Reader, 2048)
  if err != nil {
    fmt.Printf("failed to generate private key: %s\n", err)
    return
  }

  var payload []byte
  { // Create signed payload
    token := jwt.New()
    token.Set(`foo`, `bar`)
    payload, err = jwt.Sign(token, jwa.RS256, privKey)
    if err != nil {
      fmt.Printf("failed to generate signed payload: %s\n", err)
      return
    }
  }

  { // Parse signed payload
    // Use jwt.ParseVerify if you want to make absolutely sure that you
    // are going to verify the signatures every time
    token, err := jwt.Parse(bytes.NewReader(payload), jwt.WithVerify(jwa.RS256, &privKey.PublicKey))
    if err != nil {
      fmt.Printf("failed to parse JWT token: %s\n", err)
      return
    }
    buf, err := json.MarshalIndent(token, "", "  ")
    if err != nil {
      fmt.Printf("failed to generate JSON: %s\n", err)
      return
    }
    fmt.Printf("%s\n", buf)
  }
}

func ExampleToken() {
  t := jwt.New()
  t.Set(jwt.SubjectKey, `https://github.com/lestrrat-go/jwx/jwt`)
  t.Set(jwt.AudienceKey, `Golang Users`)
  t.Set(jwt.IssuedAtKey, time.Unix(aLongLongTimeAgo, 0))
  t.Set(`privateClaimKey`, `Hello, World!`)

  buf, err := json.MarshalIndent(t, "", "  ")
  if err != nil {
    fmt.Printf("failed to generate JSON: %s\n", err)
    return
  }

  fmt.Printf("%s\n", buf)
  fmt.Printf("aud -> '%s'\n", t.Audience())
  fmt.Printf("iat -> '%s'\n", t.IssuedAt().Format(time.RFC3339))
  if v, ok := t.Get(`privateClaimKey`); ok {
    fmt.Printf("privateClaimKey -> '%s'\n", v)
  }
  fmt.Printf("sub -> '%s'\n", t.Subject())
}

Documentation

Overview

Package jwt implements JSON Web Tokens as described in https://tools.ietf.org/html/rfc7519

This file is auto-generated by jwt/internal/cmd/gentoken/main.go. DO NOT EDIT

Index

Examples

Constants

View Source
const (
	AudienceKey   = "aud"
	ExpirationKey = "exp"
	IssuedAtKey   = "iat"
	IssuerKey     = "iss"
	JwtIDKey      = "jti"
	NotBeforeKey  = "nbf"
	SubjectKey    = "sub"
)

Variables

This section is empty.

Functions

func Sign added in v1.0.0

func Sign(t Token, method jwa.SignatureAlgorithm, key interface{}) ([]byte, error)

Sign is a convenience function to create a signed JWT token serialized in compact form. `key` must match the key type required by the given signature method `method`

Example
package main

import (
	"bytes"
	"crypto/rand"
	"crypto/rsa"
	"encoding/json"
	"fmt"

	"github.com/lestrrat-go/jwx/jwa"
	"github.com/lestrrat-go/jwx/jwt"
)

func main() {
	privKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Printf("failed to generate private key: %s\n", err)
		return
	}

	var payload []byte
	{ // Create signed payload
		token := jwt.New()
		token.Set(`foo`, `bar`)
		payload, err = jwt.Sign(token, jwa.RS256, privKey)
		if err != nil {
			fmt.Printf("failed to generate signed payload: %s\n", err)
			return
		}
	}

	{ // Parse signed payload
		// Use jwt.ParseVerify if you want to make absolutely sure that you
		// are going to verify the signatures every time
		token, err := jwt.Parse(bytes.NewReader(payload), jwt.WithVerify(jwa.RS256, &privKey.PublicKey))
		if err != nil {
			fmt.Printf("failed to parse JWT token: %s\n", err)
			return
		}
		buf, err := json.MarshalIndent(token, "", "  ")
		if err != nil {
			fmt.Printf("failed to generate JSON: %s\n", err)
			return
		}
		fmt.Printf("%s\n", buf)
	}
}
Output:

{
  "foo": "bar"
}

func Verify added in v1.0.0

func Verify(t Token, options ...Option) error

Verify makes sure that the essential claims stand.

See the various `WithXXX` functions for optional parameters that can control the behavior of this method.

Types

type ClaimPair added in v0.9.1

type ClaimPair = mapiter.Pair

type Clock

type Clock interface {
	Now() time.Time
}

type ClockFunc

type ClockFunc func() time.Time

func (ClockFunc) Now

func (f ClockFunc) Now() time.Time

type Iterator added in v1.0.0

type Iterator = mapiter.Iterator

type Option

type Option = option.Interface

func WithAcceptableSkew

func WithAcceptableSkew(dur time.Duration) Option

WithAcceptableSkew specifies the duration in which exp and nbf claims may differ by. This value should be positive

func WithAudience

func WithAudience(s string) Option

WithAudience specifies that expected audience value. Verify will return true if one of the values in the `aud` element matches this value. If not specified, the value of issuer is not verified at all.

func WithClaimValue added in v0.9.2

func WithClaimValue(name string, v interface{}) Option

WithClaimValue specifies that expected any claim value.

func WithClock

func WithClock(c Clock) Option

WithClock specifies the `Clock` to be used when verifying claims exp and nbf.

func WithIssuer

func WithIssuer(s string) Option

WithIssuer specifies that expected issuer value. If not specified, the value of issuer is not verified at all.

func WithJwtID

func WithJwtID(s string) Option

WithJwtID specifies that expected jti value. If not specified, the value of jti is not verified at all.

func WithOpenIDClaims added in v1.0.0

func WithOpenIDClaims() Option

WithOpenIDClaims is passed to the various JWT parsing functions, and specifies that it should use an instance of `openid.Token` as the destination to store the parsed results.

This is exactly equivalent to specifying `jwt.WithToken(openid.New())`

func WithSubject

func WithSubject(s string) Option

WithSubject specifies that expected subject value. If not specified, the value of subject is not verified at all.

func WithToken added in v1.0.0

func WithToken(t Token) Option

WithToken specifies the token instance that is used when parsing JWT tokens.

func WithVerify

func WithVerify(alg jwa.SignatureAlgorithm, key interface{}) Option

type Token

type Token interface {
	Audience() []string
	Expiration() time.Time
	IssuedAt() time.Time
	Issuer() string
	JwtID() string
	NotBefore() time.Time
	Subject() string
	PrivateClaims() map[string]interface{}
	Get(string) (interface{}, bool)
	Set(string, interface{}) error
	Iterate(context.Context) Iterator
	Walk(context.Context, Visitor) error
	AsMap(context.Context) (map[string]interface{}, error)
}

Token represents a generic JWT token. which are type-aware (to an extent). Other claims may be accessed via the `Get`/`Set` methods but their types are not taken into consideration at all. If you have non-standard claims that you must frequently access, consider creating accessors functions like the following

func SetFoo(tok jwt.Token) error func GetFoo(tok jwt.Token) (*Customtyp, error)

Embedding jwt.Token into another struct is not recommended, becase jwt.Token needs to handle private claims, and this really does not work well when it is embedded in other structure

Example
t := jwt.New()
t.Set(jwt.SubjectKey, `https://github.com/lestrrat-go/jwx/jwt`)
t.Set(jwt.AudienceKey, `Golang Users`)
t.Set(jwt.IssuedAtKey, time.Unix(aLongLongTimeAgo, 0))
t.Set(`privateClaimKey`, `Hello, World!`)

buf, err := json.MarshalIndent(t, "", "  ")
if err != nil {
	fmt.Printf("failed to generate JSON: %s\n", err)
	return
}

fmt.Printf("%s\n", buf)
fmt.Printf("aud -> '%s'\n", t.Audience())
fmt.Printf("iat -> '%s'\n", t.IssuedAt().Format(time.RFC3339))
if v, ok := t.Get(`privateClaimKey`); ok {
	fmt.Printf("privateClaimKey -> '%s'\n", v)
}
fmt.Printf("sub -> '%s'\n", t.Subject())
Output:

{
  "aud": [
    "Golang Users"
  ],
  "iat": 233431200,
  "sub": "https://github.com/lestrrat-go/jwx/jwt",
  "privateClaimKey": "Hello, World!"
}
aud -> '[Golang Users]'
iat -> '1977-05-25T18:00:00Z'
privateClaimKey -> 'Hello, World!'
sub -> 'https://github.com/lestrrat-go/jwx/jwt'

func New

func New() Token

New creates a standard token, with minimal knowledge of possible claims. Standard claims include"aud", "exp", "iat", "iss", "jti", "nbf" and "sub". Convenience accessors are provided for these standard claims

func Parse

func Parse(src io.Reader, options ...Option) (Token, error)

Parse parses the JWT token payload and creates a new `jwt.Token` object. The token must be encoded in either JSON format or compact format.

If the token is signed and you want to verify the payload, you must pass the jwt.WithVerify(alg, key) option. If you do not specify these parameters, no verification will be performed.

func ParseBytes

func ParseBytes(s []byte, options ...Option) (Token, error)

ParseString calls Parse with the given byte sequence

func ParseString

func ParseString(s string, options ...Option) (Token, error)

ParseString calls Parse with the given string

func ParseVerify

func ParseVerify(src io.Reader, alg jwa.SignatureAlgorithm, key interface{}) (Token, error)

ParseVerify is a function that is similar to Parse(), but does not allow for parsing without signature verification parameters.

type VerifyParameters

type VerifyParameters interface {
	Algorithm() jwa.SignatureAlgorithm
	Key() interface{}
}

type Visitor added in v0.9.1

type Visitor = iter.MapVisitor

type VisitorFunc added in v1.0.0

type VisitorFunc iter.MapVisitorFunc

Directories

Path Synopsis
internal
Package openid provides a specialized token that provides utilities to work with OpenID JWT tokens.
Package openid provides a specialized token that provides utilities to work with OpenID JWT tokens.

Jump to

Keyboard shortcuts

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