jwt

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2020 License: MIT Imports: 14 Imported by: 0

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 = token.Sign(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. DO NOT EDIT

Index

Examples

Constants

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

Key names for standard claims

Variables

This section is empty.

Functions

This section is empty.

Types

type ClaimPair added in v0.9.1

type ClaimPair struct {
	Name  string
	Value interface{}
}

ClaimPair is the struct returned from the iterator used in the Claims() method

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

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

type StringList

type StringList []string

func (*StringList) Accept

func (l *StringList) Accept(v interface{}) error

func (*StringList) UnmarshalJSON

func (l *StringList) UnmarshalJSON(data []byte) error

type Token

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

Token represents a JWT token. The object has convenience accessors to 7 standard claims including "aud", "exp", "iat", "iss", "jti", "nbf" and "sub" 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 wrapping the token in a wrapper by embedding the jwt.Token type in it

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 new empty JWT token

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.

func (*Token) AsMap added in v0.9.1

func (t *Token) AsMap(ctx context.Context) (map[string]interface{}, error)

AsMap returns the representation of the token as a map[string]interface{}. If you are dealing with small tokens and you are not repeatedly calling this function, this will most likely suffice in many cases. If you are either dealing with large-ish tokens and/or using it in a code path where you may want to use the Claims() method directly

func (Token) Audience

func (t Token) Audience() StringList

func (*Token) Claims added in v0.9.1

func (t *Token) Claims(octx context.Context) <-chan ClaimPair

Claims returns an iterator that returns all claims

func (Token) Expiration

func (t Token) Expiration() time.Time

func (*Token) Get

func (t *Token) Get(s string) (interface{}, bool)

func (Token) IssuedAt

func (t Token) IssuedAt() time.Time

func (Token) Issuer

func (t Token) Issuer() string

func (Token) JwtID

func (t Token) JwtID() string

func (Token) MarshalJSON

func (t Token) MarshalJSON() ([]byte, error)

MarshalJSON serializes the token in JSON format. This exists to allow flattening of private claims.

func (Token) NotBefore

func (t Token) NotBefore() time.Time

func (*Token) Set

func (t *Token) Set(name string, v interface{}) error

func (*Token) Sign

func (t *Token) Sign(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`

func (*Token) Size added in v0.9.1

func (t *Token) Size() int

Size returns the number of valid claims stored in this token

func (Token) Subject

func (t Token) Subject() string

func (*Token) UnmarshalJSON

func (t *Token) UnmarshalJSON(data []byte) error

UnmarshalJSON deserializes data from a JSON data buffer into a Token

func (*Token) Verify

func (t *Token) Verify(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.

func (*Token) Walk added in v0.9.1

func (t *Token) Walk(octx context.Context, v Visitor) error

Walk is a convenience function over the Claims() method that allows you to not deal with ClaimPair structs directly

type VerifyParameters

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

type VisitFunc added in v0.9.1

type VisitFunc func(string, interface{}) error

VisitFunc is a type of Visitor whose actual definition is a stateless function

func (VisitFunc) Visit added in v0.9.1

func (fn VisitFunc) Visit(key string, value interface{}) error

Visit implements the Visitor interace

type Visitor added in v0.9.1

type Visitor interface {
	Visit(string, interface{}) error
}

Visitor is used to examine each element of the token.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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