jwt

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2021 License: MIT Imports: 11 Imported by: 26

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

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 Clock

type Clock interface {
	Now() time.Time
}

type ClockFunc

type ClockFunc func() time.Time

func (ClockFunc) Now

func (f ClockFunc) Now() time.Time

type NumericDate

type NumericDate struct {
	time.Time
}

NumericDate represents the date format used in the 'nbf' claim

func (*NumericDate) Accept

func (n *NumericDate) Accept(v interface{}) error

func (*NumericDate) Get

func (n *NumericDate) Get() time.Time

func (NumericDate) MarshalJSON

func (n NumericDate) MarshalJSON() ([]byte, error)

MarshalJSON generates JSON representation of this instant

func (*NumericDate) UnmarshalJSON

func (n *NumericDate) UnmarshalJSON(data []byte) error

UnmarshalJSON parses the JSON representation and initializes this NumericDate

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 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 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,
  "privateClaimKey": "Hello, World!",
  "sub": "https://github.com/lestrrat/go-jwx/jwt"
}
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) Audience

func (t Token) Audience() string

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)

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

func (t Token) Subject() string

func (*Token) UnmarshalJSON

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

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.

type VerifyParameters

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

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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