tokenbridge

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2025 License: MIT Imports: 28 Imported by: 0

README

🔐 TokenBridge

Build Status Go Reference goreportcard

TokenBridge is a lightweight and flexible Go library designed to bridge identity systems securely. It enables you to verify ID tokens, exchange them for signed access tokens, and serve JSON Web Key Sets (JWKS) for downstream token validation.


✨ Features

  • ID Token Verification
    Validate OIDC-issued ID tokens using flexible verification options.

  • 🔁 Token Exchange
    Transform ID tokens into signed access tokens with optional custom claims.

  • 🔑 JWKS Generation
    Serve JSON Web Key Sets to allow downstream systems to verify your tokens.

  • 🌐 Flexible Routing
    Route token exchanges based on ID token claims using regex-based matching.


🧭 Architecture

Here's how TokenBridge works in a typical token exchange flow:

+-------------------+       +-------------------+       +-------------------+
|                   |       |                   |       |                   |
|      Client       |       |   TokenBridge     |       |   OIDC Provider   |
|                   |       |                   |       |                   |
+-------------------+       +-------------------+       +-------------------+
          |                           |                           |
          |   1. Sends ID Token       |                           |
          +-------------------------->|                           |
          |                           |                           |
          |                           |   2. Verifies ID Token    |
          |                           +-------------------------->|
          |                           |                           |
          |   3. Returns Access Token |                           |
          +<--------------------------+                           |
          |                           |                           |

🧩 Components

👤 Client
  • Sends an ID token to TokenBridge for verification.
  • Receives a newly issued access token.
🔐 TokenBridge
  • Verifies ID tokens using an OIDC provider.
  • Issues signed access tokens with support for custom claims.
  • Serves a JWKS endpoint for public key distribution.
  • Routes token exchanges based on ID Token claims.
🪪 OIDC Provider
  • Issues standards-compliant ID tokens.
  • Works with any OIDC-compatible identity provider (e.g., Auth0, Google, Okta).

Looking to integrate or extend TokenBridge? Check out these related projects:

🤝 Contributing

We welcome contributions! Feel free to open issues, share feedback, or submit pull requests to improve TokenBridge.

📄 License

TokenBridge is licensed under the MIT License.

Documentation

Overview

Package tokenbridge provides functionality to interact with an authentication system. It allows verifying ID tokens, exchanging them for access tokens, and retrieving the JSON Web Key Set (JWKS) from the authorization server.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CalculateThumbprintFromJWKS added in v0.0.3

func CalculateThumbprintFromJWKS(jwksURI *url.URL, optFns ...func(o *CalculateThumbprintOptions)) (string, error)

CalculateThumbprintFromJWKS retrieves the certificate chain from the JWKS URI, extracts the last certificate, and calculates its thumbprint (SHA-1).

func DefaultOnTokenCreate added in v0.0.8

func DefaultOnTokenCreate(_ context.Context, issuer string, idToken *oidc.IDToken) (jwt.MapClaims, error)

DefaultOnTokenCreate is the default implementation of the OnTokenCreate callback. It generates a set of default claims based on the provided ID token. This function can be overridden by the user to customize the claims as needed. The default implementation includes the issuer, subject, and audience claims. It returns a map of claims that will be included in the generated access token. The "sub" claim is set to the subject of the ID token, and the "iss" claim is set to the issuer of the ID token. The "aud" claim is set to the audience of the ID token.

Types

type Cache added in v0.1.0

type Cache interface {
	// Add inserts a public key into the cache with the specified key ID.
	Add(ctx context.Context, keyID string, key crypto.PublicKey)

	// Get retrieves a public key from the cache by its key ID.
	// Returns nil if the key is not found.
	Get(ctx context.Context, keyID string) (crypto.PublicKey, bool)
}

Cache defines the interface for a thread-safe cache that stores public keys.

func NewMemoryCache added in v0.1.0

func NewMemoryCache() Cache

NewMemoryCache creates a new instance of the memory cache.

func NewNoopCache added in v0.1.0

func NewNoopCache() Cache

NewNoopCache creates a new instance of the noop cache.

type CalculateThumbprintOptions added in v0.0.3

type CalculateThumbprintOptions struct {
	// TLSConfig is a customizable TLS configuration used when establishing the TLS connection.
	TLSConfig *tls.Config

	// Dialer is a custom network dialer that will be used to establish the network connection.
	Dialer *net.Dialer
}

CalculateThumbprintOptions holds configuration for CalculateThumbprintFromJWKS

type ClientCredentialIssuer added in v0.0.10

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

ClientCredentialIssuer is responsible for issuing access tokens using the client credentials flow.

func NewClientCredentialIssuer added in v0.0.10

func NewClientCredentialIssuer(config *clientcredentials.Config) *ClientCredentialIssuer

NewClientCredentialIssuer creates a new ClientCredentialIssuer instance.

Parameters:

  • config: A clientcredentials.Config instance containing the OAuth2 client credentials configuration.

Returns:

  • A new ClientCredentialIssuer instance.

func (*ClientCredentialIssuer) IssueAccessToken added in v0.0.10

func (cci *ClientCredentialIssuer) IssueAccessToken(ctx context.Context, _ *oidc.IDToken) (string, error)

IssueAccessToken generates an access token using the client credentials flow.

Parameters:

  • ctx: The context used for making requests.

Returns:

  • The access token as a string if successful.
  • An error if there is a problem generating the access token.

type ECSignerOptions added in v0.1.0

type ECSignerOptions struct {
	RotatedKeys []RotatedECDAKey
}

ECSignerOptions provides options for rotating ECDA keys.

type JWK added in v0.1.0

type JWK struct {
	// Kty (Key Type) indicates the algorithm family of the key (e.g., "RSA", "EC").
	Kty string `json:"kty"`

	// Alg (Algorithm) indicates the algorithm used with the key (e.g., "RS256").
	Alg string `json:"alg"`

	// Use (Key Use) indicates the intended use of the key (e.g., "sig" for signature).
	Use string `json:"use"`

	// Kid (Key ID) is a unique identifier for the key.
	Kid string `json:"kid"`

	// N is the modulus for RSA keys. This field is only set for RSA keys.
	N string `json:"n,omitempty"`

	// E is the exponent for RSA keys. This field is only set for RSA keys.
	E string `json:"e,omitempty"`

	// X is the x-coordinate for EC keys. This field is only set for EC keys.
	X string `json:"x,omitempty"`

	// Y is the y-coordinate for EC keys. This field is only set for EC keys.
	Y string `json:"y,omitempty"`

	// Crv (Curve) indicates the elliptic curve used for EC keys. This field is only set for EC keys.
	Crv string `json:"crv,omitempty"`
}

JWK represents a single JSON Web Key, which contains parameters describing the key. It can be an RSA or EC key, and includes information such as key type, algorithm, key usage, key ID, and other parameters depending on the key type.

type JWKS added in v0.1.0

type JWKS struct {
	// Keys is a list of JSON Web Keys (JWKs) included in the set.
	Keys []JWK `json:"keys"`
}

JWKS represents a JSON Web Key Set (JWKS), which contains an array of keys that can be used for validating JWTs. Each key in the set is a JWK.

func ParseJWKS added in v0.1.0

func ParseJWKS(data []byte) (*JWKS, error)

ParseJWKS parses a JSON Web Key Set (JWKS) from a JSON-encoded byte slice.

The data parameter should be a valid JWKS JSON string. This function will parse the string into a JWKS struct, which contains a list of JWKs.

Returns: - *JWKS: The parsed JWKS struct. - error: An error, if any occurred during parsing.

type JWKSProvider added in v0.0.10

type JWKSProvider interface {
	// GetJWKS retrieves the JSON Web Key Set (JWKS) containing the public keys used to verify the signed tokens.
	GetJWKS(ctx context.Context) (*JWKS, error)
}

JWKSProvider defines an additional interface for retrieving the JWKS.

type KMSClient added in v0.1.0

type KMSClient interface {
	// Sign signs a digest with the given key using KMS.
	Sign(ctx context.Context, input *kms.SignInput, optFns ...func(*kms.Options)) (*kms.SignOutput, error)

	// GetPublicKey retrieves the public key associated with the given key ID.
	GetPublicKey(ctx context.Context, input *kms.GetPublicKeyInput, optFns ...func(*kms.Options)) (*kms.GetPublicKeyOutput, error)
}

KMSClient defines the methods that are needed from AWS KMS client for signing tokens and fetching public keys.

type KMSSigner added in v0.2.0

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

KMSSigner represents a signer that uses AWS Key Management Service (KMS) to sign JWT tokens.

func (*KMSSigner) GetJWKS added in v0.2.0

func (s *KMSSigner) GetJWKS(ctx context.Context) (*JWKS, error)

GetJWKS retrieves the JSON Web Key Set (JWKS) containing the public keys used for verifying signed tokens.

Parameters:

  • ctx: The context to use for the public key retrieval request.

Returns:

  • A JWKS containing the public key(s) for verifying the token signature.
  • An error if retrieving the public key or constructing the JWKS fails.

func (*KMSSigner) KeyID added in v0.2.0

func (s *KMSSigner) KeyID() string

KeyID returns the ID of the KMS key used for signing.

func (*KMSSigner) SignToken added in v0.2.0

func (s *KMSSigner) SignToken(ctx context.Context, token *jwt.Token) (string, error)

SignToken signs a JWT token using the KMS service. It serializes the token, computes the hash, and then signs it using KMS.

Parameters:

  • ctx: The context to use for the signing request.
  • token: The JWT token that needs to be signed.

Returns:

  • The signed JWT token as a string.
  • An error if the signing process fails.

func (*KMSSigner) SigningMethod added in v0.2.0

func (s *KMSSigner) SigningMethod() jwt.SigningMethod

SigningMethod returns the JWT signing method corresponding to the KMS signing algorithm.

type KMSSignerOptions added in v0.2.0

type KMSSignerOptions struct {
	Cache         Cache    // Cache for storing and retrieving public keys
	RotatedKeyIDs []string // A list of key IDs that have been rotated out of active use but are still included in the JWKS
}

KMSOptions defines the configuration options for the KMS signer. It allows customization of the cache used for storing and retrieving public keys. The default cache is a no-op cache, which means it does not store any keys. You can provide a custom cache implementation that implements the Cache interface.

type OIDCVerifier

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

OIDCVerifier is responsible for verifying OpenID Connect ID tokens. It uses an OIDC provider and supports various verification options, including client ID validation, expiry checks, and issuer checks.

func NewOIDCVerifier

func NewOIDCVerifier(ctx context.Context, issuerURL *url.URL, clientIDs []string, optFns ...func(o *OIDCVerifierOptions)) (*OIDCVerifier, error)

NewOIDCVerifier creates a new OIDCVerifier instance using the provided configuration options.

Parameters:

  • ctx: The context used for making requests.
  • issuer: The URL of the OpenID Connect provider.
  • clientIDs: A list of allowed client IDs to validate the ID token against.
  • optFns: A variadic list of functions to customize the OIDCVerifierOptions.

Returns:

  • A new OIDCVerifier instance.

func (*OIDCVerifier) ClientIDs

func (p *OIDCVerifier) ClientIDs() []string

ClientIDs returns the list of allowed client IDs for which the ID token will be verified.

func (*OIDCVerifier) Issuer

func (p *OIDCVerifier) Issuer() string

Issuer returns the URL of the OpenID Connect provider used by the OIDCVerifier.

func (*OIDCVerifier) Verify

func (p *OIDCVerifier) Verify(ctx context.Context, rawIDToken string) (*oidc.IDToken, error)

Verify verifies the provided raw ID token using the configured client IDs and the OpenID Connect provider.

Parameters:

  • ctx: The context used for making requests.
  • rawIDToken: The raw ID token string that needs to be verified.

Returns:

  • A verified *oidc.IDToken if verification is successful.
  • An error if verification fails for all client IDs.

type OIDCVerifierOptions

type OIDCVerifierOptions struct {
	// Transport is an optional custom HTTP transport used for making HTTP requests.
	Transport http.RoundTripper

	// Thumbprints is a list of valid thumbprints for the keys used to verify ID tokens.
	// If this is set, the transport will be configured to validate the thumbprints of the keys.
	Thumbprints []string

	// SupportedSigningAlgs is a list of signing algorithms supported for verifying ID tokens.
	SupportedSigningAlgs []string

	// SkipClientIDCheck controls whether the client ID check is skipped during verification.
	SkipClientIDCheck bool

	// SkipExpiryCheck controls whether the expiry check is skipped during verification.
	SkipExpiryCheck bool

	// SkipIssuerCheck controls whether the issuer check is skipped during verification.
	SkipIssuerCheck bool

	// Now is a function that returns the current time, which can be used for expiry and validity checks.
	// If not provided, the default time function (time.Now) is used.
	Now func() time.Time

	// CalculateThumbprintOptions is an optional configuration for calculating the thumbprint.
	// It allows customization of the TLS configuration and dialer used to establish the connection.
	// This is useful for scenarios where you need to specify custom TLS settings or a custom dialer.
	// If nil, default settings will be used.
	CalculateThumbprintOptions *CalculateThumbprintOptions
}

OIDCVerifierOptions defines the available configuration options for the OIDCVerifier. These options control the behavior of the verification process, such as enabling or disabling specific checks (e.g., issuer, client ID, expiry), and controlling the supported signing algorithms.

type RSASignerOptions added in v0.1.0

type RSASignerOptions struct {
	RotatedKeys []RotatedRSAKey
}

RSASignerOptions provides options for rotating RSA keys.

type RotatedECDAKey added in v0.1.0

type RotatedECDAKey struct {
	KeyID     string
	PublicKey *ecdsa.PublicKey
}

RotatedECDAKey holds information about rotated ECDA keys.

type RotatedRSAKey added in v0.1.0

type RotatedRSAKey struct {
	KeyID     string
	PublicKey *rsa.PublicKey
}

RotatedRSAKey holds information about rotated RSA keys.

type Signer

type Signer interface {
	// SignToken signs the given JWT token using the signing algorithm and returns the signed string.
	SignToken(ctx context.Context, token *jwt.Token) (string, error)

	// GetJWKS returns the JWKS (JSON Web Key Set) associated with the signer, containing the public key.
	GetJWKS(ctx context.Context) (*JWKS, error)

	// SigningMethod returns the JWT signing method (e.g., HMAC or RSA).
	SigningMethod() jwt.SigningMethod

	// KeyID returns the Key ID used to identify the key.
	KeyID() string
}

Signer is an interface that defines methods for signing JWT tokens, retrieving JWKS (JSON Web Key Sets), and providing the signing method and key ID for the signer.

func NewEC256Signer added in v0.1.0

func NewEC256Signer(privateKey *ecdsa.PrivateKey, keyID string, optFns ...func(*ECSignerOptions)) Signer

NewEC256Signer creates a new EC signer using the ES256 signing method.

func NewEC384Signer added in v0.1.0

func NewEC384Signer(privateKey *ecdsa.PrivateKey, keyID string, optFns ...func(*ECSignerOptions)) Signer

NewEC384Signer creates a new EC signer using the ES384 signing method.

func NewEC512Signer added in v0.1.0

func NewEC512Signer(privateKey *ecdsa.PrivateKey, keyID string, optFns ...func(*ECSignerOptions)) Signer

NewEC512Signer creates a new EC signer using the ES512 signing method.

func NewHMAC256Signer

func NewHMAC256Signer(secret, keyID string) Signer

NewHMAC256Signer creates a new HMAC signer using the HS256 signing method.

func NewHMAC384Signer

func NewHMAC384Signer(secret, keyID string) Signer

NewHMAC384Signer creates a new HMAC signer using the HS384 signing method.

func NewHMAC512Signer

func NewHMAC512Signer(secret, keyID string) Signer

NewHMAC512Signer creates a new HMAC signer using the HS512 signing method.

func NewKMSSigner added in v0.2.0

func NewKMSSigner(kmsClient KMSClient, keyID string, alg types.SigningAlgorithmSpec, optFns ...func(o *KMSSignerOptions)) Signer

NewKMSSigner creates a new instance of KMSSigner with the given client, key ID, and signing algorithm. It also accepts optional configuration functions to customize the KMSOptions.

func NewRSA256Signer

func NewRSA256Signer(privateKey *rsa.PrivateKey, keyID string, optFns ...func(*RSASignerOptions)) Signer

NewRSA256Signer creates a new RSA signer using the RS256 signing method.

func NewRSA384Signer

func NewRSA384Signer(privateKey *rsa.PrivateKey, keyID string, optFns ...func(*RSASignerOptions)) Signer

NewRSA384Signer creates a new RSA signer using the RS384 signing method.

func NewRSA512Signer

func NewRSA512Signer(privateKey *rsa.PrivateKey, keyID string, optFns ...func(*RSASignerOptions)) Signer

NewRSA512Signer creates a new RSA signer using the RS512 signing method.

type TokenBridge

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

TokenBridge is the main struct that facilitates interaction between an OIDC (OpenID Connect) verifier and a token issuer. It provides methods to verify ID tokens, exchange them for access tokens, and retrieve the JWKS used to verify the tokens.

func New

func New(oidcVerifier *OIDCVerifier) *TokenBridge

New creates and returns a new TokenBridge instance. This function initializes the TokenBridge with an OIDCVerifier to enable token exchange and verification.

func (*TokenBridge) AddRoute added in v0.0.10

func (tb *TokenBridge) AddRoute(claims map[string]string, issuer TokenIssuer) error

AddRoute registers a route with specific claims and a corresponding TokenIssuer. The `claims` map can contain regular expressions as values for flexible matching.

func (*TokenBridge) ExchangeToken

func (tb *TokenBridge) ExchangeToken(ctx context.Context, rawIDToken string) (string, error)

ExchangeToken exchanges a raw ID token for an access token. It first verifies the ID token using the OIDCVerifier, and then creates an access token using the TokenIssuer.

Parameters: - ctx: The context for managing the request lifecycle. - rawIDToken: The raw ID token to be verified and exchanged.

Returns: - The created access token string. - An error if there was an issue during the token exchange process.

func (*TokenBridge) SetDefaultIssuer added in v0.0.10

func (tb *TokenBridge) SetDefaultIssuer(issuer TokenIssuer)

SetDefaultIssuer sets a default TokenIssuer to be used when no routes match the claims. This allows the TokenBridge to handle cases where no specific route is defined for the claims.

type TokenIssuer added in v0.0.10

type TokenIssuer interface {
	// IssueAccessToken generates an access token based on the provided ID token.
	IssueAccessToken(ctx context.Context, idToken *oidc.IDToken) (string, error)
}

TokenIssuer defines an interface for issuing access tokens.

type TokenIssuerWithJWKS added in v0.0.10

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

TokenIssuerWithJWKS is responsible for creating and signing access tokens for authenticated users. It implements both the TokenIssuer and JWKSProvider interfaces.

func NewTokenIssuerWithJWKS added in v0.0.10

func NewTokenIssuerWithJWKS(iss string, signer Signer, optFns ...func(o *TokenIssuerWithJWKSOptions)) *TokenIssuerWithJWKS

NewTokenIssuerWithJWKS creates a new TokenIssuerWithJWKS instance with the provided signer and optional configuration functions.

Parameters:

  • signer: A Signer implementation used to sign the generated access tokens.
  • optFns: A variadic list of functions to customize the TokenIssuerWithJWKSOptions.

Returns:

  • A new TokenIssuerWithJWKS instance configured with the provided options.

func (*TokenIssuerWithJWKS) GetJWKS added in v0.0.10

func (ti *TokenIssuerWithJWKS) GetJWKS(ctx context.Context) (*JWKS, error)

GetJWKS retrieves the JSON Web Key Set (JWKS) containing the public keys used to verify the signed tokens.

Parameters:

  • ctx: The context used for making requests.

Returns:

  • The JWKS containing the public key(s) used for verifying tokens.
  • An error if there is a problem retrieving the JWKS.

func (*TokenIssuerWithJWKS) IssueAccessToken added in v0.0.10

func (ti *TokenIssuerWithJWKS) IssueAccessToken(ctx context.Context, idToken *oidc.IDToken) (string, error)

IssueAccessToken generates an access token based on the provided OIDC ID token.

Parameters:

  • ctx: The context used for making requests.
  • idToken: The ID token obtained from the OIDC provider, which will be used to create the access token.
  • customClaims: A map of custom claims to be added to the access token. Claims like "sub" and "exp" are reserved and cannot be overwritten.

Returns:

  • The signed JWT access token as a string if successful.
  • An error if there is a problem generating or signing the token.

type TokenIssuerWithJWKSOptions added in v0.0.10

type TokenIssuerWithJWKSOptions struct {
	// MandatoryClaims are the claims that must be present in the access token.
	MandatoryClaims []string

	// TokenExpiration defines the duration for which the access token will be valid.
	// The default is set to one hour.
	TokenExpiration time.Duration

	// OnTokenCreate is a callback function that allows customization of claims during token creation.
	// If not set, a default implementation will be used.
	OnTokenCreate func(ctx context.Context, issuer string, idToken *oidc.IDToken) (jwt.MapClaims, error)
}

TokenIssuerWithJWKSOptions defines the configuration options for the TokenIssuerWithJWKS. These options control the behavior of the token issuer, such as token expiration and subject overwriting.

type Verifier added in v0.0.10

type Verifier interface {
	Verify(ctx context.Context, rawIDToken string) (*oidc.IDToken, error)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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