jwt

package
v1.8.1 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 4 Imported by: 0

README

jwt

Generic JWT issuer/verifier with pluggable signing algorithms. The root jwt package defines Signer/Verifier interfaces and AuthService[T] for typed payloads; algorithm-specific subpackages (jwt/hs256 today; RS256/EdDSA/JWKS planned) implement the interfaces.

When to use

Any service issuing or validating JWTs for authentication, service-to-service auth, or download links.

Quickstart

package main

import (
    "log"
    "time"

    "github.com/sergeyslonimsky/core/jwt"
    "github.com/sergeyslonimsky/core/jwt/hs256"
)

type AuthInfo struct {
    UserID int    `json:"user_id"`
    Role   string `json:"role"`
}

func main() {
    signer := hs256.NewSigner([]byte("super-secret"))
    verifier := hs256.NewVerifier([]byte("super-secret"))

    svc := jwt.NewAuthService[AuthInfo](
        signer, verifier,
        "myservice", "user", time.Hour,
    )

    token, err := svc.CreateToken(AuthInfo{UserID: 42, Role: "admin"})
    if err != nil { log.Fatal(err) }

    info, err := svc.ParseToken(token)
    if err != nil { log.Fatal(err) }
    log.Printf("user %d (%s)", info.UserID, info.Role)
}

API

// core/jwt
type Signer interface {
    Sign(claims jwt.Claims) (string, error)
}
type Verifier interface {
    Verify(tokenString string, dst jwt.Claims) error
}

type AuthClaims[T any] struct {
    jwt.RegisteredClaims
    AuthInfo T `json:"authInfo"`
}

type AuthService[T any] struct { /* opaque */ }

func NewAuthService[T any](signer Signer, verifier Verifier, serviceName, claimSubject string, ttl time.Duration) *AuthService[T]
func (s *AuthService[T]) CreateToken(authInfo T) (string, error)
func (s *AuthService[T]) ParseToken(tokenString string) (T, error)
// core/jwt/hs256
func NewSigner(secret []byte) *Signer
func NewVerifier(secret []byte) *Verifier

// Legacy generic helpers (kept for non-AuthService use)
func CreateToken[T jwt.Claims](secret []byte, claims T) (string, error)
func ParseToken[T jwt.Claims](tokenString string, secret []byte) (T, error)

Algorithm support

Algorithm Status
HS256 (HMAC-SHA256) jwt/hs256
RS256 (RSA-SHA256) planned (jwt/rs256)
EdDSA planned (jwt/eddsa)
JWKS-backed multi-key verifier planned (jwt/jwks)

New algorithms drop in by implementing jwt.Signer and/or jwt.Verifier. AuthService and downstream code are unchanged.

Lifecycle

JWT is stateless — no Resource, Runner, or Healthchecker. Signers and verifiers are plain values with no background work; nothing to register with app.App.

Testing

For unit tests, construct a Signer + Verifier with a known secret and round-trip tokens. See hs256/jwt_test.go for the pattern.

See also

Documentation

Overview

Package jwt provides a small framework for issuing and parsing JWT tokens with a generic claims payload, plus signer/verifier interfaces that allow swapping the signing algorithm without changing call sites.

The HS256 implementation lives in core/jwt/hs256. Future algorithm subpackages (RS256, EdDSA, JWKS) implement the Signer/Verifier interfaces and are dropped in without breaking AuthService callers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthClaims

type AuthClaims[T any] struct {
	jwt.RegisteredClaims

	AuthInfo T `json:"authInfo"`
}

AuthClaims embeds the standard jwt.RegisteredClaims and adds a caller-defined typed payload accessible as AuthInfo.

type AuthService

type AuthService[T any] struct {
	// contains filtered or unexported fields
}

AuthService issues and parses tokens carrying a typed AuthInfo payload. Construct via NewAuthService with a Signer and Verifier from one of the algorithm subpackages.

func NewAuthService

func NewAuthService[T any](
	signer Signer,
	verifier Verifier,
	serviceName, claimSubject string,
	tokenTTL time.Duration,
) *AuthService[T]

NewAuthService builds an AuthService.

signer and verifier come from the chosen algorithm subpackage, e.g.:

signer := hs256.NewSigner([]byte("secret"))
verifier := hs256.NewVerifier([]byte("secret"))
svc := jwt.NewAuthService[MyAuthInfo](signer, verifier, "my-service", "user", time.Hour)

serviceName is used as the Issuer and Audience claims; claimSubject becomes the Subject claim; tokenTTL bounds the ExpiresAt claim.

func (*AuthService[T]) CreateToken

func (s *AuthService[T]) CreateToken(authInfo T) (string, error)

CreateToken issues a fresh signed token containing authInfo. Sets all standard claims (iss, sub, aud, iat, nbf, exp, jti).

func (*AuthService[T]) ParseToken

func (s *AuthService[T]) ParseToken(tokenString string) (T, error)

ParseToken validates the given JWT and returns its AuthInfo payload.

type Signer added in v1.3.0

type Signer interface {
	// Sign returns the signed JWT string.
	Sign(claims jwt.Claims) (string, error)
}

Signer issues a signed JWT for the given claims. Implemented per algorithm in core/jwt/<algo> subpackages.

type Verifier added in v1.3.0

type Verifier interface {
	Verify(tokenString string, dst jwt.Claims) error
}

Verifier parses and validates a JWT, populating dst with the claims. dst must be a pointer to a jwt.Claims-compatible struct (e.g., *AuthClaims[T]). Returns an error on signature mismatch, expired tokens, or malformed input.

Directories

Path Synopsis
Package hs256 implements jwt.Signer and jwt.Verifier using the HS256 HMAC-SHA256 signing algorithm.
Package hs256 implements jwt.Signer and jwt.Verifier using the HS256 HMAC-SHA256 signing algorithm.

Jump to

Keyboard shortcuts

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