jwt

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2025 License: 0BSD Imports: 15 Imported by: 0

README

jwt

A library to handle JWT in Go. Limited to HMAC-SHA and Ed25519 only.

Usage

import "git.sr.ht/~gbrlsnchs/jwt"

var alg = jwt.NewHS256([]byte("secret"))

type Claims struct {
	jwt.RegisteredClaims
	Foo string `json:"foo"`
	Bar string `json:"bar"`
}

func sign(claims Claims) ([]byte, error) {
	token, err := jwt.Sign(claims, alg, nil)
	if err != nil {
		return nil, err
	}
	return token, nil
}

func verify(token []byte) (*Claims, error) {
	jot, err := jwt.Verify(token, alg, nil)
	if err != nil {
		return nil, err
	}
	return &jot.Claims, nil
}
Validating default claims
import (
	"time"

	"git.sr.ht/~gbrlsnchs/jwt"
)

var alg = jwt.NewHS256([]byte("secret"))

type Claims struct {
	jwt.RegisteredClaims
	Foo string `json:"foo"`
	Bar string `json:"bar"`
}

func sign(claims Claims) ([]byte, error) {
	token, err := jwt.Sign(claims, alg, nil)
	if err != nil {
		return nil, err
	}
	return token, nil
}

func verify(token []byte) (*Claims, error) {
	now := time.Now()

	var vd jwt.Validator
	opts := &jwt.VerifyOptions[Claims]{
		Validators: []jwt.ValidatorFunc{
			vd.ExpirationTime(now),
		},
	}
	jot, err := jwt.Verify(token, alg, opts)
	if err != nil {
		return nil, err
	}
	return &jot.Claims, nil
}
Replacing algorithm based on key ID
import (
	"time"

	"git.sr.ht/~gbrlsnchs/jwt"
)

var defaultAlg = jwt.NewHS256([]byte("secret_foo"))

var algs = map[string]jwt.Algorithm{
	"foo": defaultArg,
	"bar": jwt.NewHS256([]byte("secret_bar")),
}

type Claims struct {
	jwt.RegisteredClaims
	Foo string `json:"foo"`
	Bar string `json:"bar"`
}

func sign(claims Claims, keyID string) ([]byte, error) {
	opts := &jwt.SignOptions{
		KeyID: kid,
	}
	token, err := jwt.Sign(claims, algs[keyID], nil)
	if err != nil {
		return nil, err
	}
	return token, nil
}

func verify(token []byte) (*Claims, error) {
	now := time.Now()

	var vd jwt.Validator
	opts := &jwt.VerifyOptions[Claims]{
		ReplaceAlgorithm: func(jot *jwt.JWT[Claims]) jwt.Algorithm {
			return algs[jot.Header.KeyID]
		},
		Validators: []jwt.ValidatorFunc{
			vd.ExpirationTime(now),
		},
	}
	jot, err := jwt.Verify(token, defaultAlg, opts)
	if err != nil {
		return nil, err
	}
	return &jot.Claims, nil
}

Documentation

Overview

Package jwt is a JSON Web Token signer, verifier and validator.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEd25519NilPrivKey is the error for trying to sign a JWT with a nil private key.
	ErrEd25519NilPrivKey = errors.New("jwt: Ed25519 private key is nil")
	// ErrEd25519NilPubKey is the error for trying to verify a JWT with a nil public key.
	ErrEd25519NilPubKey = errors.New("jwt: Ed25519 public key is nil")
	// ErrEd25519Verification is the error for when verification with Ed25519 fails.
	ErrEd25519Verification = errors.New("jwt: Ed25519 verification failed")
)
View Source
var (
	// ErrHMACMissingKey is the error for trying to sign or verify a JWT with an empty key.
	ErrHMACMissingKey = errors.New("jwt: HMAC key is empty")
	// ErrHMACVerification is the error for an invalid signature.
	ErrHMACVerification = errors.New("jwt: HMAC verification failed")
)
View Source
var (
	ErrMalformed     = errors.New("jwt: token is malformed")
	ErrAlgValidation = errors.New(`jwt: "alg" header doesn't match chosen algorithm`)
)
View Source
var (
	// ErrAudValidation is the error for an invalid "aud" claim.
	ErrAudValidation = errors.New("jwt: aud claim is invalid")
	// ErrExpValidation is the error for an invalid "exp" claim.
	ErrExpValidation = errors.New("jwt: exp claim is invalid")
	// ErrIatValidation is the error for an invalid "iat" claim.
	ErrIatValidation = errors.New("jwt: iat claim is invalid")
	// ErrIssValidation is the error for an invalid "iss" claim.
	ErrIssValidation = errors.New("jwt: iss claim is invalid")
	// ErrJtiValidation is the error for an invalid "jti" claim.
	ErrJtiValidation = errors.New("jwt: jti claim is invalid")
	// ErrNbfValidation is the error for an invalid "nbf" claim.
	ErrNbfValidation = errors.New("jwt: nbf claim is invalid")
	// ErrSubValidation is the error for an invalid "sub" claim.
	ErrSubValidation = errors.New("jwt: sub claim is invalid")
)

Functions

func Ed25519PrivateKey

func Ed25519PrivateKey(priv ed25519.PrivateKey) func(*Ed25519)

Ed25519PrivateKey is an option to set a private key to the Ed25519 algorithm.

func Ed25519PublicKey

func Ed25519PublicKey(pub ed25519.PublicKey) func(*Ed25519)

Ed25519PublicKey is an option to set a public key to the Ed25519 algorithm.

func Sign

func Sign[T WithRegisteredClaims](claims T, alg Algorithm, opts *SignOptions) ([]byte, error)

Types

type Algorithm

type Algorithm interface {
	Name() string
	Sign(headerPayload []byte) ([]byte, error)
	Size() int
	Verify(headerPayload, sig []byte) error
}

Algorithm is an algorithm for both signing and verifying a JWT.

type Audience

type Audience []string

Audience is a special claim that may either be a single string or an array of strings, as per the RFC 7519.

func (Audience) MarshalJSON

func (a Audience) MarshalJSON() ([]byte, error)

MarshalJSON implements a marshaling function for "aud" claim.

func (*Audience) UnmarshalJSON

func (a *Audience) UnmarshalJSON(b []byte) error

UnmarshalJSON implements an unmarshaling function for "aud" claim.

type Ed25519

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

Ed25519 is an algorithm that uses EdDSA to sign SHA-512 hashes.

func NewEd25519

func NewEd25519(opts ...func(*Ed25519)) *Ed25519

NewEd25519 creates a new algorithm using EdDSA and SHA-512.

func (*Ed25519) Name

func (*Ed25519) Name() string

Name returns the algorithm's name.

func (*Ed25519) Sign

func (ed *Ed25519) Sign(headerPayload []byte) ([]byte, error)

Sign signs headerPayload using the Ed25519 algorithm.

func (*Ed25519) Size

func (*Ed25519) Size() int

Size returns the signature byte size.

func (*Ed25519) Verify

func (ed *Ed25519) Verify(payload, sig []byte) (err error)

Verify verifies a payload and a signature.

type HMACSHA

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

HMACSHA is an algorithm that uses HMAC to sign SHA hashes.

func NewHS256

func NewHS256(key []byte) *HMACSHA

NewHS256 creates a new algorithm using HMAC and SHA-256.

func NewHS384

func NewHS384(key []byte) *HMACSHA

NewHS384 creates a new algorithm using HMAC and SHA-384.

func NewHS512

func NewHS512(key []byte) *HMACSHA

NewHS512 creates a new algorithm using HMAC and SHA-512.

func (*HMACSHA) Name

func (hs *HMACSHA) Name() string

Name returns the algorithm's name.

func (*HMACSHA) Sign

func (hs *HMACSHA) Sign(headerPayload []byte) ([]byte, error)

Sign signs headerPayload using the HMAC-SHA algorithm.

func (*HMACSHA) Size

func (hs *HMACSHA) Size() int

Size returns the signature's byte size.

func (*HMACSHA) Verify

func (hs *HMACSHA) Verify(headerPayload, sig []byte) (err error)

Verify verifies a signature based on headerPayload using HMAC-SHA.

type Header struct {
	Algorithm   string `json:"alg,omitempty"`
	ContentType string `json:"cty,omitempty"`
	KeyID       string `json:"kid,omitempty"`
	Type        string `json:"typ,omitempty"`
}

Header is a JOSE header narrowed down to the JWT specification from RFC 7519.

Parameters are ordered according to the RFC 7515.

type JWT

type JWT[T WithRegisteredClaims] struct {
	Header Header
	Claims T
}

func Verify

func Verify[T WithRegisteredClaims](token []byte, alg Algorithm, opts *VerifyOptions[T]) (*JWT[T], error)

type None

type None struct{}

None is an unsecured algorithm.

func (None) Name

func (None) Name() string

Name always returns "none".

func (None) Sign

func (None) Sign(_ []byte) ([]byte, error)

Sign always returns a nil byte slice and a nil error.

func (None) Size

func (None) Size() int

Size always returns 0 and a nil error.

func (None) Verify

func (None) Verify(_, _ []byte) error

Verify always returns a nil error.

type RegisteredClaims

type RegisteredClaims struct {
	Issuer     string   `json:"iss,omitempty"`
	Subject    string   `json:"sub,omitempty"`
	Audience   Audience `json:"aud,omitempty"`
	Expiration *Time    `json:"exp,omitempty"`
	NotBefore  *Time    `json:"nbf,omitempty"`
	IssuedAt   *Time    `json:"iat,omitempty"`
	JWTID      string   `json:"jti,omitempty"`
}

RegisteredClaims represents the set of registered claims according to the RFC 7519.

func (RegisteredClaims) RegisteredClaimsSet

func (c RegisteredClaims) RegisteredClaimsSet() RegisteredClaims

type SignOptions

type SignOptions struct {
	KeyID       string
	ContentType string
}

type Time

type Time struct {
	time.Time
}

Time is the allowed format for time, as per the RFC 7519.

func NumericDate

func NumericDate(tt time.Time) *Time

NumericDate is a resolved Unix time.

func (Time) MarshalJSON

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

MarshalJSON implements a marshaling function for time-related claims.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

UnmarshalJSON implements an unmarshaling function for time-related claims.

type Validator

type Validator struct{}

func (Validator) Audience

func (Validator) Audience(aud Audience) ValidatorFunc

Audience validates the "aud" claim. It checks if at least one of the audiences in the JWT's payload is listed in aud.

func (Validator) ExpirationTime

func (Validator) ExpirationTime(now time.Time) ValidatorFunc

ExpirationTime validates the "exp" claim.

func (Validator) ID

func (Validator) ID(jti string) ValidatorFunc

ID validates the "jti" claim.

func (Validator) IssuedAt

func (Validator) IssuedAt(now time.Time) ValidatorFunc

IssuedAt validates the "iat" claim.

func (Validator) Issuer

func (Validator) Issuer(iss string) ValidatorFunc

Issuer validates the "iss" claim.

func (Validator) NotBefore

func (Validator) NotBefore(now time.Time) ValidatorFunc

NotBefore validates the "nbf" claim.

func (Validator) Subject

func (Validator) Subject(sub string) ValidatorFunc

Subject validates the "sub" claim.

type ValidatorFunc

type ValidatorFunc func(RegisteredClaims) error

ValidatorFunc is a function that validates a Payload pointer.

type VerifyOptions

type VerifyOptions[T WithRegisteredClaims] struct {
	CheckAlgorithm   bool
	ReplaceAlgorithm func(*JWT[T]) Algorithm
	Validators       []ValidatorFunc
}

type WithRegisteredClaims

type WithRegisteredClaims interface {
	RegisteredClaimsSet() RegisteredClaims
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳