JWT Manager

JWT Manager provides a reusable and extensible interface for creating and validating JSON Web Tokens (JWTs) in Go, supporting both HMAC (HS256) and RSA (RS256) signing methods.

Features

  • Token Creation: Generate signed JWT tokens with custom claims.

  • Token Validation: Parse and validate tokens with support for custom claims.

  • Pluggable Signing Methods: Easily switch between HS256 (HMAC) and RS256 (RSA).

Installation

go get github.com/kittipat1413/go-common/util/jwt

Usage

JWTManager Interface

type JWTManager interface {
    CreateToken(ctx context.Context, claims jwt.Claims) (string, error)
    ParseAndValidateToken(ctx context.Context, tokenString string, claims jwt.Claims) error
}
  • CreateToken: Generates a signed JWT token with the provided claims.

    • Params:

      • ctx: Context for request tracing or cancellation.

      • claims: Claims to include in the token (must implement jwt.Claims).

    • Returns: Signed token string or an error.

  • ParseAndValidateToken: Parses and validates a JWT token, populating the provided claims struct.

    • Params:

      • ctx: Context for request tracing or cancellation.

      • tokenString: The JWT token string to validate.

      • claims: Pointer to a claims struct to populate (must implement jwt.Claims).

    • Returns: Error if validation fails; otherwise, populates the provided claims struct.

Examples

You can find a complete working example in the repository under util/jwt/example.

Last updated