jwt v1

A Go package that provides a simple and secure way to work with JSON Web Tokens (JWT). This package supports both HMAC (secret-based) and RSA (key-based) signing methods.

Repository

Features

  • Simple API for creating and managing JWT claims

  • Support for all standard JWT claims

  • HMAC-SHA256 signing with secret key

  • RSA-SHA256 signing with public/private key pairs

  • Token verification and decoding

  • Custom claim support

Installation

go get github.com/metadiv-io/jwt

Usage

Creating Claims

// Create new claims
claims := jwt.NewClaims()
// Set standard claims
claims.SetIssuer("my-app")
claims.SetSubject("user-123")
claims.SetAudience("api-service")
claims.SetExpirationTime(time.Now().Add(24 time.Hour))
claims.SetIssuedAt(time.Now())
claims.SetNotBefore(time.Now())
claims.SetID("unique-token-id")
// Set custom claims
claims.SetValue("role", "admin")
claims.SetValue("permissions", []string{"read", "write"})

Encoding Tokens

/ Using HMAC (secret)
secret := "your-secret-key"
token, err := jwt.EncodeWithSecret(claims, secret)
if err != nil {
    // Handle error
}
// Using RSA (private key)
privateKey := // your RSA private key
token, err := jwt.EncodeWithKey(claims, privateKey)
if err != nil {
    // Handle error
}

Decoding Tokens

// Decode and verify with secret
claims, err := jwt.DecodeWithSecret(token, secret)
if err != nil {
    // Handle error
}
// Decode and verify with public key
publicKey := // your RSA public key
claims, err := jwt.DecodeWithKey(token, publicKey)
if err != nil {
    // Handle error
}
// Decode without verification (use with caution)
claims, err := jwt.DecodeUnverified(token)
if err != nil {
    // Handle error
}

Accessing Claims

// Get standard claims
issuer := claims.GetIssuer()
subject := claims.GetSubject()
audience := claims.GetAudience()
expirationTime := claims.GetExpirationTime()
issuedAt := claims.GetIssuedAt()
notBefore := claims.GetNotBefore()
id := claims.GetID()
// Get custom claims
role := claims.GetValue("role")

Standard Claims

The package supports all standard JWT claims:

  • iss (Issuer)

  • sub (Subject)

  • aud (Audience)

  • exp (Expiration Time)

  • nbf (Not Before)

  • iat (Issued At)

  • jti (JWT ID)

Security Considerations

  1. Always use strong secrets or properly generated RSA keys

  2. Set appropriate expiration times for tokens

  3. Avoid using DecodeUnverified in production environments

  4. Keep private keys secure and never expose them

  5. Validate tokens on the server side before trusting their contents

Dependencies

  • github.com/golang-jwt/jwt/v5

  • github.com/metadiv-io/rsa

Last updated