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 ¶
- func GetServiceID(ctx context.Context) string
- func GetServiceName(ctx context.Context) string
- func HasPermission(ctx context.Context, permission string) bool
- type Bundle
- func (b *Bundle) GenerateServiceToken(permissions []string) (string, error)
- func (b *Bundle) GenerateToken(serviceID, serviceName string, permissions []string) (string, error)
- func (b *Bundle) HTTPMiddleware(next http.Handler) http.Handler
- func (b *Bundle) Initialize(app *framework.App) error
- func (b *Bundle) Name() string
- func (b *Bundle) RequirePermissions(permissions ...string) func(http.Handler) http.Handler
- func (b *Bundle) Stop(ctx context.Context) error
- func (b *Bundle) UnaryClientInterceptor() grpc.UnaryClientInterceptor
- func (b *Bundle) UnaryServerInterceptor() grpc.UnaryServerInterceptor
- func (b *Bundle) ValidateToken(tokenString string) (*ServiceClaims, error)
- type Config
- type ServiceClaims
- type TokenValidator
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetServiceID ¶
GetServiceID returns the authenticated service ID from context.
func GetServiceName ¶
GetServiceName returns the authenticated service name from context.
Types ¶
type Bundle ¶
type Bundle struct {
// contains filtered or unexported fields
}
Bundle provides JWT authentication for Forge applications.
func (*Bundle) GenerateServiceToken ¶
GenerateServiceToken creates a token for this service to authenticate with other services.
func (*Bundle) GenerateToken ¶
GenerateToken creates a new JWT token for service-to-service communication.
func (*Bundle) HTTPMiddleware ¶
HTTPMiddleware returns HTTP middleware for JWT authentication.
func (*Bundle) Initialize ¶
Initialize sets up JWT authentication.
func (*Bundle) RequirePermissions ¶
RequirePermissions returns middleware that requires specific permissions.
func (*Bundle) Stop ¶
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.
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.