jwt

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package jwt provides JWT authentication bundle for secure inter-service communication.

The JWT bundle provides:

  • JWT token validation and signing
  • gRPC authentication interceptors for both client and server
  • HTTP authentication middleware
  • Token propagation between services
  • Service identity management
  • Configurable token validation (expiry, audience, issuer)

Basic Usage

Configure JWT authentication for your service:

jwtConfig := jwt.Config{
	SecretKey:     []byte("your-secret-key"),
	Issuer:        "auth-service",
	Audience:      "forge-services",
	TokenDuration: 24 * time.Hour,
	ServiceName:   "user-service",
}

jwtBundle := jwt.NewBundle(jwtConfig)

app, err := framework.New(
	framework.WithConfig(&baseConfig),
	framework.WithBundle(jwtBundle),
)

Service-to-Service Authentication

The bundle automatically adds authentication to gRPC calls:

// Client side (automatic token injection)
conn, err := grpc.Dial("target-service:8080",
	grpc.WithUnaryInterceptor(jwtBundle.UnaryClientInterceptor()),
)

// Server side (automatic token validation)
app, err := framework.New(
	framework.WithGRPCInterceptor(jwtBundle.UnaryServerInterceptor()),
)

HTTP Authentication

Secure HTTP endpoints with JWT middleware:

// Protect specific endpoints
protectedMux := http.NewServeMux()
protectedMux.HandleFunc("/api/users", userHandler)

// Apply JWT middleware
http.Handle("/api/", jwtBundle.HTTPMiddleware(protectedMux))

Token Claims

Access authenticated service information in handlers:

func userHandler(ctx context.Context, req *UserRequest) (*UserResponse, error) {
	claims := jwt.ClaimsFromContext(ctx)
	if claims == nil {
		return nil, status.Errorf(codes.Unauthenticated, "no authentication")
	}

	serviceID := claims.ServiceID
	// ... use service identity for authorization
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetServiceID

func GetServiceID(ctx context.Context) string

GetServiceID returns the authenticated service ID from context.

func GetServiceName

func GetServiceName(ctx context.Context) string

GetServiceName returns the authenticated service name from context.

func HasPermission

func HasPermission(ctx context.Context, permission string) bool

HasPermission checks if the authenticated service has the specified permission.

Types

type Bundle

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

Bundle provides JWT authentication for Forge applications.

func NewBundle

func NewBundle(config Config) *Bundle

NewBundle creates a new JWT authentication bundle.

func (*Bundle) GenerateServiceToken

func (b *Bundle) GenerateServiceToken(permissions []string) (string, error)

GenerateServiceToken creates a token for this service to authenticate with other services.

func (*Bundle) GenerateToken

func (b *Bundle) GenerateToken(serviceID, serviceName string, permissions []string) (string, error)

GenerateToken creates a new JWT token for service-to-service communication.

func (*Bundle) HTTPMiddleware

func (b *Bundle) HTTPMiddleware(next http.Handler) http.Handler

HTTPMiddleware returns HTTP middleware for JWT authentication.

func (*Bundle) Initialize

func (b *Bundle) Initialize(app *framework.App) error

Initialize sets up JWT authentication.

func (*Bundle) Name

func (b *Bundle) Name() string

Name returns the bundle name.

func (*Bundle) RequirePermissions

func (b *Bundle) RequirePermissions(permissions ...string) func(http.Handler) http.Handler

RequirePermissions returns middleware that requires specific permissions.

func (*Bundle) Stop

func (b *Bundle) Stop(ctx context.Context) error

Stop implements the Bundle interface for graceful shutdown. JWT bundle has no persistent resources requiring cleanup.

func (*Bundle) UnaryClientInterceptor

func (b *Bundle) UnaryClientInterceptor() grpc.UnaryClientInterceptor

UnaryClientInterceptor returns a gRPC client interceptor for JWT token injection.

func (*Bundle) UnaryServerInterceptor

func (b *Bundle) UnaryServerInterceptor() grpc.UnaryServerInterceptor

UnaryServerInterceptor returns a gRPC server interceptor for JWT authentication.

func (*Bundle) ValidateToken

func (b *Bundle) ValidateToken(tokenString string) (*ServiceClaims, error)

ValidateToken validates a JWT token and returns the claims.

type Config

type Config struct {
	// SecretKey is the HMAC secret key for signing and validating tokens.
	// This should be a strong, random key shared across all services.
	SecretKey []byte

	// Issuer is the JWT issuer claim (typically your auth service).
	Issuer string

	// Audience is the JWT audience claim (typically your service mesh or organization).
	Audience string

	// TokenDuration is how long tokens remain valid.
	TokenDuration time.Duration

	// ServiceName is the name of this service (used in service-to-service tokens).
	ServiceName string

	// ClockSkew is the allowed time difference when validating token timestamps.
	ClockSkew time.Duration

	// RequireHTTPS enforces HTTPS for HTTP authentication (recommended for production).
	RequireHTTPS bool

	// SkipPaths are HTTP paths that don't require authentication.
	SkipPaths []string
}

Config contains JWT authentication configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible secure defaults.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the JWT configuration.

type ServiceClaims

type ServiceClaims struct {
	jwt.RegisteredClaims
	ServiceID   string   `json:"service_id"`
	ServiceName string   `json:"service_name"`
	Permissions []string `json:"permissions,omitempty"`
}

ServiceClaims represents the claims in a service-to-service JWT token.

func ClaimsFromContext

func ClaimsFromContext(ctx context.Context) *ServiceClaims

ClaimsFromContext extracts JWT claims from the context.

type TokenValidator

type TokenValidator interface {
	ValidateToken(ctx context.Context, claims *ServiceClaims) error
}

TokenValidator provides an interface for custom token validation logic.

Jump to

Keyboard shortcuts

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