jwt

package
v0.0.0-...-98622c7 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package jwt provides functions for creating, parsing, and verifying JSON Web Tokens (JWT) as defined in RFC 7519, with support for JSON Web Keys (JWK) per RFC 7517.

It supports EdDSA (Ed25519), ECDSA (P-256/P-384/P-521), RSA (PKCS1v15 and PSS), and HMAC (SHA-256/384/512) signing and verification.

Sign, ParseHeader, ParseAndVerify

The following example demonstrates the complete JWT lifecycle: signing a token, inspecting its header, and verifying signature and claims.

import "github.com/skerkour/stdx-go/jwt"

 // Generate or load a key pair (Ed25519 shown here).
 _, priv, _ := ed25519.GenerateKey(rand.Reader)
 pub := priv.Public().(ed25519.PublicKey)

 // Sign a token.
 header := jwt.Header{Typ: jwt.JWT, Alg: jwt.EdDSA, KID: "my-key"}
 claims := map[string]any{"sub": "user123", "exp": time.Now().Add(time.Hour).Unix()}
 token, err := jwt.Sign(priv, &header, claims)
 if err != nil { log.Fatal(err) }

 // ParseHeader extracts the header without verifying (useful for kid lookup).
 parsedHeader, err := jwt.ParseHeader(token)
 if err != nil { log.Fatal(err) }
 fmt.Println("Key ID:", parsedHeader.KID)

 // ParseAndVerify verifies the signature, validates claims, and decodes claims.
 opts := jwt.VerifyOptions{Exp: true, AllowedTimeDrift: time.Minute}
 result, err := jwt.ParseAndVerify[map[string]any](pub, &parsedHeader, token, &opts)
 if err != nil { log.Fatal(err) }
 fmt.Println("Subject:", result["sub"])

JWK

Encode a Go crypto key to JWK JSON using json.Marshal, and parse it back using json.Unmarshal:

import "github.com/skerkour/stdx-go/jwt"

 // Marshal a key to RFC 7517 JWK JSON.
 _, priv, _ := ed25519.GenerateKey(rand.Reader)
 jwk := jwt.JWK{Key: priv, Alg: jwt.EdDSA, ID: "my-key-id"}
 jwkJSON, err := json.Marshal(jwk)
 if err != nil { log.Fatal(err) }
 fmt.Println(string(jwkJSON))

 // Unmarshal JWK JSON back into a Go crypto key.
 var parsed jwt.JWK
 if err := json.Unmarshal(jwkJSON, &parsed); err != nil { log.Fatal(err) }
 fmt.Printf("Algorithm: %s, Key ID: %s\n", parsed.Alg, parsed.ID)
 _ = parsed.Key.(ed25519.PrivateKey)

 // Parse a JWK Set (JWKS):
 var set struct { Keys []jwt.JWK `json:"keys"` }
 if err := json.Unmarshal(jwksJSON, &set); err != nil { log.Fatal(err) }

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnsupportedKeyType   = errors.New("jwt: unsupported key type")
	ErrUnsupportedCurve     = errors.New("jwt: unsupported elliptic curve")
	ErrInvalidAlgorithm     = errors.New("jwt: invalid algorithm for key type")
	ErrInvalidJWK           = errors.New("jwt: invalid JWK")
	ErrMissingField         = errors.New("jwt: missing required JWT field")
	ErrInvalidSignature     = errors.New("jwt: invalid signature")
	ErrInvalidToken         = errors.New("jwt: invalid token format")
	ErrTokenExpired         = errors.New("jwt: token is expired")
	ErrTokenNotYetValid     = errors.New("jwt: token is not yet valid")
	ErrTokenIssuedInFuture  = errors.New("jwt: token was issued in the future")
	ErrInvalidAudience      = errors.New("jwt: invalid audience")
	ErrInvalidIssuer        = errors.New("jwt: invalid issuer")
	ErrKeyIsTooShort        = errors.New("jwt: key is too short")
	ErrUnsupportedAlgorithm = errors.New("jwt: unsupported algorithm")
)

Functions

func ParseAndVerify

func ParseAndVerify[C any](key any, header Header, token string, opts *VerifyOptions) (claims C, err error)

ParseAndVerify verifies the JWT signature, validates claims per opts, and unmarshals the claims into dst (which must be a pointer).

Supported key types for verification:

ed25519.PrivateKey / ed25519.PublicKey  -> EdDSA
*ecdsa.PrivateKey / *ecdsa.PublicKey    -> ES256/ES384/ES512
*rsa.PublicKey                          -> RS*/PS*
[]byte                                  -> HS*

func Sign

func Sign(keyAny any, header *Header, claims any) (string, error)

Sign creates a signed JWT token string.

Supported key types for signing:

ed25519.PrivateKey  -> EdDSA
*ecdsa.PrivateKey   -> ES256/ES384/ES512 (derived from curve)
[]byte              -> HS256/HS384/HS512 (must match header alg)

Types

type Algorithm

type Algorithm string

Algorithm identifies the signing/verification algorithm for a JWT.

const (
	// HMAC using SHA-256.
	HS256 Algorithm = "HS256"

	// HMAC using SHA-384.
	HS384 Algorithm = "HS384"

	// HMAC using SHA-512.
	HS512 Algorithm = "HS512"

	// Edwards-curve Digital Signature Algorithm (Ed25519).
	EdDSA Algorithm = "EdDSA"

	// ECDSA using P-256 and SHA-256.
	ES256 Algorithm = "ES256"

	// ECDSA using P-384 and SHA-384.
	ES384 Algorithm = "ES384"

	// ECDSA using P-521 and SHA-512.
	ES512 Algorithm = "ES512"

	// RSASSA-PKCS1-v1.5 with SHA-256.
	RS256 Algorithm = "RS256"

	// RSASSA-PKCS1-v1.5 with SHA-384.
	RS384 Algorithm = "RS384"

	// RSASSA-PKCS1-v1.5 with SHA-512.
	RS512 Algorithm = "RS512"

	// RSASSA-PSS with SHA-256.
	PS256 Algorithm = "PS256"

	// RSASSA-PSS with SHA-384.
	PS384 Algorithm = "PS384"

	// RSASSA-PSS with SHA-512.
	PS512 Algorithm = "PS512"

	// ML-DSA (Module-Lattice-Based Digital Signature Standard, FIPS 204).
	MLDSA44 Algorithm = "ML-DSA-44"
	MLDSA65 Algorithm = "ML-DSA-65"
	MLDSA87 Algorithm = "ML-DSA-87"
)

type ClaimsValidator

type ClaimsValidator interface {
	ValidateClaims(opts *VerifyOptions) error
}

The ClaimsValidator interface is used to avoid multiple unmarshalling when validating registered claims.

type Header struct {
	Typ     TokenType `json:"typ"`
	Alg     Algorithm `json:"alg"`
	CTY     string    `json:"cty,omitempty"`
	JKU     string    `json:"jku,omitempty"`
	KID     string    `json:"kid,omitempty"`
	X5U     string    `json:"x5u,omitempty"`
	X5C     []string  `json:"x5c,omitempty"`
	X5T     string    `json:"x5t,omitempty"`
	X5TS256 string    `json:"x5t#S256,omitempty"`
	// contains filtered or unexported fields
}

Header represents a JWT header.

func ParseHeader

func ParseHeader(token string) (Header, error)

ParseHeader extracts and decodes the header from a JWT token without verifying. Use this to inspect the kid field before looking up the verification key.

type JWK

type JWK struct {
	// Key ID
	ID  string
	Alg Algorithm
	Key any
}

JWK holds the decoded key and its JWK metadata. Returned by value to minimize allocations.

func (JWK) MarshalJSON

func (jwk JWK) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for JWK. It serializes the key to RFC 7517 JSON.

func (*JWK) UnmarshalJSON

func (jwk *JWK) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for JWK. It decodes a JSON Web Key and populates j.Key, j.Alg, and j.ID.

type JWKS

type JWKS struct {
	Keys []JWK `json:"keys"`
}

type RegisteredClaims

type RegisteredClaims struct {
	ISS string   `json:"iss,omitempty"`
	SUB string   `json:"sub,omitempty"`
	AUD []string `json:"aud,omitempty"`
	EXP int64    `json:"exp,omitempty"`
	NBF int64    `json:"nbf,omitempty"`
	IAT int64    `json:"iat,omitempty"`
	JTI string   `json:"jti,omitempty"`
}

RegisteredClaims holds the standard JWT registered claim names. https://www.rfc-editor.org/rfc/rfc7519#section-4.1

func (RegisteredClaims) ValidateClaims

func (claims RegisteredClaims) ValidateClaims(opts *VerifyOptions) error

type TokenType

type TokenType string

TokenType represents the type of a JWT token.

const JWT TokenType = "JWT"

type VerifyOptions

type VerifyOptions struct {
	AllowedTimeDrift time.Duration
	Exp              bool
	// Not Before verification
	Nbf bool
	// Issued At verification
	Iat bool
	// Audience verification
	Aud []string
	// Issuer verification
	Iss []string
}

VerifyOptions configures claim verification for ParseAndVerify.

Jump to

Keyboard shortcuts

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