### JWT Asymmetric Key Distribution Architecture Diagram Source: https://github.com/krajcik/go-jwt/blob/main/README.md Illustrates the flow of private and public keys in an asymmetric JWT setup. The Auth Service signs tokens with a private key from a Key Store, while Client Services verify tokens using public keys distributed from the Key Store. ```text ┌─────────────────┐ Private Key ┌─────────────────┐ │ Auth Service │ ◄─────────────── │ Key Store │ │ (Token Signing) │ │ │ └─────────────────┘ └─────────────────┘ │ │ │ Tokens │ Public Key ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ │ Client Service │ ◄─────────────── │ Client Service │ │ (Verify) │ Public Key │ (Verify) │ └─────────────────┘ └─────────────────┘ ``` -------------------------------- ### Implement Custom Claims Validation in Go Source: https://github.com/krajcik/go-jwt/blob/main/README.md Illustrates how to implement the `ClaimsValidator` interface for custom JWT claims. Provides an example with `UserClaims` that validates `UserID` and `Email` format, ensuring data integrity upon token verification. ```go type ClaimsValidator interface { Validate() error } type UserClaims struct { UserID string `json:"user_id"` Email string `json:"email"` } func (c UserClaims) Validate() error { if c.UserID == "" { return errors.New("user_id cannot be empty") } emailRegex := regexp.MustCompile(`^[^s@]+@[^s@]+\.[^s@]+$`) if c.Email != "" && !emailRegex.MatchString(c.Email) { return errors.New("invalid email format") } return nil } ``` -------------------------------- ### Go JWT Library Testing Commands Source: https://github.com/krajcik/go-jwt/blob/main/README.md Provides common `go test` commands for the JWT library. Includes commands to run all tests, generate test coverage reports, and execute specific test functions. ```bash # Run all tests go test ./... -v # Run tests with coverage go test ./... -cover # Run specific test go test ./... -run TestTokenSigner -v ``` -------------------------------- ### Git Workflow for Contributing to Go JWT Source: https://github.com/krajcik/go-jwt/blob/main/README.md Detailed steps for developers to contribute to the Go JWT repository, covering the standard branch-commit-push cycle after forking the repository and before opening a pull request. ```shell git checkout -b feature/amazing-feature git commit -m 'Add some amazing feature' git push origin feature/amazing-feature ``` -------------------------------- ### Go JWT Token Verification for Client Service Source: https://github.com/krajcik/go-jwt/blob/main/README.md This Go code illustrates how a client service can verify JWT tokens using the `go-jwt` package in a verification-only mode. It defines its own `ClientClaims` structure, uses a public key (obtained from the authentication service) to create a token verifier, and then verifies an incoming token. It shows how to access both standard JWT claims (subject, expiry) and custom claims (permissions). ```Go package main import ( "crypto/rsa" "fmt" "github.com/krajcik/go-jwt" ) // Client service defines its own claims structure type ClientClaims struct { UserID string `json:"user_id"` Permissions []string `json:"permissions"` } func main() { // Client service only has public key var publicKey *rsa.PublicKey // obtained from Auth Service // Create token verifier (verification-only) algorithm := jwt.NewRS256WithPublicKey(publicKey) verifier, _ := jwt.NewTokenVerifier[ClientClaims](algorithm, "auth-service") // Verify token from request token := "eyJ..." // from Authorization header standardClaims, customClaims, err := verifier.VerifyToken(token) if err != nil { panic(err) } // Use standard claims userID := standardClaims.Subject expiry := standardClaims.ExpiresAt // Use custom claims permissions := customClaims.Permissions fmt.Printf("User: %s, Permissions: %v, Expires: %d\n", userID, permissions, expiry) } ``` -------------------------------- ### Go JWT Token Generation for Authentication Service Source: https://github.com/krajcik/go-jwt/blob/main/README.md This Go code demonstrates how an authentication service can generate JWT tokens using the `go-jwt` package. It defines a custom `AuthClaims` structure, generates an RSA key pair, creates a token signer with RS256 algorithm, and then generates a token with the custom claims and a specified expiration time. The `Validate` method for `AuthClaims` is optional but shown for custom validation logic. ```Go package main import ( "crypto/rand" "crypto/rsa" "fmt" "time" "github.com/krajcik/go-jwt" ) // Define your custom claims type AuthClaims struct { UserID string `json:"user_id"` Email string `json:"email"` Roles []string `json:"roles"` TokenType string `json:"token_type"` } // Implement validation (optional) func (c AuthClaims) Validate() error { if c.UserID == "" { return errors.New("user_id is required") } return nil } func main() { // Generate RSA key pair for Auth Service privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) // Create token signer algorithm := jwt.NewRS256(privateKey) signer, _ := jwt.NewTokenSigner[AuthClaims](algorithm, "auth-service") // Generate token with custom claims customClaims := AuthClaims{ UserID: "user_12345", Email: "user@example.com", Roles: []string{"user", "admin"}, TokenType: "access", } token, err := signer.GenerateToken("user_12345", time.Hour, customClaims) if err != nil { panic(err) } fmt.Println("Generated token:", token) } ``` -------------------------------- ### Define and Use Payment Specific JWT Claims in Go Source: https://github.com/krajcik/go-jwt/blob/main/README.md Defines a custom `PaymentClaims` struct for JWT tokens, including validation logic for `MaxAmount`. Shows how to verify tokens with these claims and enforce payment limits based on the token's `MaxAmount`. ```go type PaymentClaims struct { PaymentMethodID string `json:"payment_method_id"` MaxAmount float64 `json:"max_amount"` Currency string `json:"currency"` MerchantID string `json:"merchant_id"` } func (c PaymentClaims) Validate() error { if c.MaxAmount <= 0 { return errors.New("max_amount must be positive") } return nil } // Usage in payment service algorithm := jwt.NewRS256WithPublicKey(publicKey) verifier, _ := jwt.NewTokenVerifier[PaymentClaims](algorithm, "auth-service") _, paymentClaims, err := verifier.VerifyToken(token) if err != nil { return errors.New("invalid payment token") } // Validate payment amount against token limits if requestAmount > paymentClaims.MaxAmount { return errors.New("amount exceeds token limit") } ``` -------------------------------- ### Define and Use E-commerce Specific JWT Claims in Go Source: https://github.com/krajcik/go-jwt/blob/main/README.md Defines a custom `EcommerceClaims` struct for JWT tokens, including validation logic for customer tiers. Demonstrates how to verify tokens with these claims using an RS256 algorithm and extract specific e-commerce data like `CartID` and `CustomerTier`. ```go type EcommerceClaims struct { CartID string `json:"cart_id"` CustomerTier string `json:"customer_tier"` StoreID string `json:"store_id"` } func (c EcommerceClaims) Validate() error { validTiers := map[string]bool{ "bronze": true, "silver": true, "gold": true, "platinum": true, } if !validTiers[c.CustomerTier] { return errors.New("invalid customer tier") } return nil } // Usage in e-commerce service algorithm := jwt.NewRS256WithPublicKey(publicKey) verifier, _ := jwt.NewTokenVerifier[EcommerceClaims](algorithm, "auth-service") standardClaims, ecommerceClaims, err := verifier.VerifyToken(token) if err != nil { return http.StatusUnauthorized, err } // Use e-commerce specific claims cartID := ecommerceClaims.CartID customerTier := ecommerceClaims.CustomerTier ``` -------------------------------- ### Go JWT Standard Claims Definition Source: https://github.com/krajcik/go-jwt/blob/main/README.md Defines the `StandardClaims` struct, which includes common JWT fields like Subject, IssuedAt, ExpiresAt, Issuer, and Audience. These claims provide essential metadata for token management and validation. ```go type StandardClaims struct { Subject string `json:"sub"` // User/entity identifier IssuedAt int64 `json:"iat"` // Issued at timestamp ExpiresAt int64 `json:"exp"` // Expiration timestamp NotBefore int64 `json:"nbf"` // Not valid before (optional) Issuer string `json:"iss"` // Token issuer Audience string `json:"aud"` // Token audience (optional) JwtID string `json:"jti"` // JWT ID (optional) } ``` -------------------------------- ### Go JWT Token Verification Error Handling Source: https://github.com/krajcik/go-jwt/blob/main/README.md Demonstrates robust error handling for JWT token verification in Go. It shows how to differentiate between common JWT errors like `ErrExpiredToken`, `ErrInvalidSignature`, and `ErrInvalidClaims` to return appropriate HTTP statuses and messages. ```go standardClaims, customClaims, err := verifier.VerifyToken(token) if err != nil { switch err { case jwt.ErrExpiredToken: return http.StatusUnauthorized, "Token expired" case jwt.ErrInvalidSignature: return http.StatusUnauthorized, "Invalid token" case jwt.ErrInvalidClaims: return http.StatusBadRequest, "Invalid claims" default: return http.StatusInternalServerError, "Token verification failed" } } ``` -------------------------------- ### JWT HMAC Shared Secret for Internal Go Services Source: https://github.com/krajcik/go-jwt/blob/main/README.md Demonstrates how to configure JWT for internal microservices using a shared secret with the HS256 algorithm. Both services can use the same secret for signing and verifying tokens, suitable for trusted internal communication. ```go // For internal microservices that can share secrets algorithm := jwt.NewHS256("shared-internal-secret") // Both services can sign and verify signer, _ := jwt.NewTokenSigner[InternalClaims](algorithm, "internal") verifier, _ := jwt.NewTokenVerifier[InternalClaims](algorithm, "internal") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.