jwt

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package jwt provides JWT token generation and validation with configurable signing: HS256 (symmetric), RS256 (RSA, default), or ES256 (ECDSA). Secret or keys are loaded from config (env, file paths, or embedded PEM bytes via config.Server.JWTPrivateKeyPEM/JWTPublicKeyPEM).

Role in architecture:

  • Infrastructure: used by auth middleware and handlers; reads config.Server (Secret, key paths or embedded PEM) and expiry.

Responsibilities:

  • NewManager: all-in-one sign + verify; loads keys from config (env, file, or embed); returns error instead of panic.
  • NewSigner: signing only (private key or secret); use for auth/login services that issue tokens.
  • NewVerifier: verification only (public key or secret); use for API/gateway services that only validate tokens.
  • TokenVerifier interface: implemented by *Manager and *Verifier; pass to AuthMiddleware so either can be used.
  • Manager/Signer: GenerateToken, GenerateTokenWithExpiry, GenerateRefreshToken, GenerateImpersonationToken.
  • Manager/Verifier: ValidateToken.
  • ComparePassword: bcrypt. GetCurrentUserUUID: read user_id from Gin context.

Constraints:

  • Default algorithm is RS256; set JWT_SIGNING_ALGORITHM=HS256 for symmetric secret.
  • For RS256/ES256, provide keys via JWT_PRIVATE_KEY and JWT_PUBLIC_KEY (path or inline PEM), or set config.Server.JWTPrivateKeyPEM and JWTPublicKeyPEM (e.g. from //go:embed) before calling NewManager/NewSigner/NewVerifier.
  • No global state; create Manager, Signer, or Verifier via NewManager/NewSigner/NewVerifier(ctx, config).

This package must NOT:

  • Contain use-case logic; only token and password operations.

Index

Constants

View Source
const (
	TokenTypeAccess        = "access"
	TokenTypeRefresh       = "refresh"
	TokenTypeImpersonation = "impersonation"
)

TokenType identifies the kind of JWT (access, refresh, impersonation).

Variables

This section is empty.

Functions

func ComparePassword

func ComparePassword(hashedPassword, plainPassword string) bool

ComparePassword returns true if plainPassword matches the bcrypt hash hashedPassword.

func GetCurrentUserUUID added in v0.3.1

func GetCurrentUserUUID(ctx *gin.Context) (uuid.UUID, bool)

GetCurrentUserUUID reads "user_id" from the Gin context (set by auth middleware).

Types

type Claims

type Claims struct {
	UUID string `json:"uuid"`

	jwt.RegisteredClaims

	TokenType string `json:"token_type,omitempty"` // "access", "refresh", "impersonation"

	ImpersonatorID   string `json:"impersonator_id,omitempty"`
	ImpersonatorRole string `json:"impersonator_role,omitempty"`
	IsImpersonating  bool   `json:"is_impersonating,omitempty"`
	OriginalSub      string `json:"original_sub,omitempty"`
}

Claims is the JWT payload. It embeds jwt.RegisteredClaims (exp, iat, nbf, sub, iss, aud, jti) and adds UUID, TokenType, and optional impersonation fields.

type Manager added in v0.3.6

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

Manager holds JWT signing and verification configuration. Create with NewManager for all-in-one use. For split services use NewSigner (auth server) and NewVerifier (API servers).

func NewManager added in v0.3.6

func NewManager(ctx context.Context, conf *config.Configuration) (*Manager, error)

NewManager builds a JWT Manager from config: loads secret or keys from env or file paths. Returns an error instead of panicking when config is invalid or keys cannot be loaded.

func (*Manager) GenerateImpersonationToken added in v0.3.6

func (m *Manager) GenerateImpersonationToken(adminID uuid.UUID, adminRole string, targetUserID uuid.UUID, requestedTTL time.Duration) (string, error)

GenerateImpersonationToken issues a short-lived JWT for admin-as-user (token_type: "impersonation"). TTL is clamped to max 30 minutes.

func (*Manager) GenerateRefreshToken added in v0.3.6

func (m *Manager) GenerateRefreshToken(id uuid.UUID) (string, error)

GenerateRefreshToken issues a signed JWT with refresh token expiry (token_type: "refresh").

func (*Manager) GenerateToken added in v0.3.6

func (m *Manager) GenerateToken(id uuid.UUID) (string, error)

GenerateToken issues a signed JWT with the given UUID and default access token expiry (token_type: "access").

func (*Manager) GenerateTokenWithExpiry added in v0.3.6

func (m *Manager) GenerateTokenWithExpiry(id uuid.UUID, expiry time.Duration) (string, error)

GenerateTokenWithExpiry issues a signed JWT with the given UUID and custom expiry (token_type: "access").

func (*Manager) GetAccessTokenExpiry added in v0.3.6

func (m *Manager) GetAccessTokenExpiry() time.Duration

GetAccessTokenExpiry returns the access token expiry duration.

func (*Manager) ValidateToken added in v0.3.6

func (m *Manager) ValidateToken(tokenString string) (*Claims, error)

ValidateToken parses the token string, verifies signature and expiry, and returns Claims or an error. Validates alg and optional kid against the Manager.

type Signer added in v0.3.6

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

Signer issues JWTs (private key or secret only). Use for auth/login services.

func NewSigner added in v0.3.6

func NewSigner(ctx context.Context, conf *config.Configuration) (*Signer, error)

NewSigner builds a JWT Signer from config (loads only private key or secret). Use for auth services that issue tokens.

func (*Signer) GenerateImpersonationToken added in v0.3.6

func (s *Signer) GenerateImpersonationToken(adminID uuid.UUID, adminRole string, targetUserID uuid.UUID, requestedTTL time.Duration) (string, error)

GenerateImpersonationToken issues a short-lived JWT (token_type: impersonation). TTL clamped to max 30 minutes.

func (*Signer) GenerateRefreshToken added in v0.3.6

func (s *Signer) GenerateRefreshToken(id uuid.UUID) (string, error)

GenerateRefreshToken issues a signed JWT (token_type: refresh).

func (*Signer) GenerateToken added in v0.3.6

func (s *Signer) GenerateToken(id uuid.UUID) (string, error)

GenerateToken issues a signed JWT (token_type: access).

func (*Signer) GenerateTokenWithExpiry added in v0.3.6

func (s *Signer) GenerateTokenWithExpiry(id uuid.UUID, expiry time.Duration) (string, error)

GenerateTokenWithExpiry issues a signed JWT (token_type: access) with custom expiry.

type TokenVerifier added in v0.3.6

type TokenVerifier interface {
	ValidateToken(tokenString string) (*Claims, error)
}

TokenVerifier is implemented by *Manager and *Verifier. Use it in auth middleware so either can be passed.

type Verifier added in v0.3.6

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

Verifier validates JWTs (public key or secret only). Use for API/gateway services that only verify.

func NewVerifier added in v0.3.6

func NewVerifier(ctx context.Context, conf *config.Configuration) (*Verifier, error)

NewVerifier builds a JWT Verifier from config (loads only public key or secret). Use for API services that only validate tokens.

func (*Verifier) ValidateToken added in v0.3.6

func (v *Verifier) ValidateToken(tokenString string) (*Claims, error)

ValidateToken implements TokenVerifier.

Jump to

Keyboard shortcuts

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