authlib

package
v0.0.0-...-aa4210d Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2024 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package authlib provides OAuth2 token management and JWT validation functionality. It implements the OAuth2 client credentials flow for service-to-service authentication and includes efficient caching mechanisms for both access tokens and JWK Sets.

Key Features:

  • OAuth2 client credentials flow implementation
  • Automatic token refresh and caching
  • JWT token validation and parsing
  • Configurable retry mechanism
  • Context-aware operations

Example Usage:

config := authlib.OAuthConfig{
    ClientID:     "your-client-id",
    ClientSecret: "your-client-secret",
    TokenURL:     "https://auth.example.com/token",
}

cache := authlib.NewTokenCache(config)

// Optional: Configure custom retry behavior
cache.SetRetryConfig(authlib.RetryConfig{
    MaxAttempts: 3,
    WaitTime:    time.Second,
})

// Get a token (automatically handles caching and refresh)
token, err := cache.GetToken(context.Background())

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type OAuthConfig

type OAuthConfig struct {
	RetryConfig RetryConfig

	// ClientID is the OAuth client identifier
	ClientID string

	// ClientSecret is the OAuth client secret
	ClientSecret string

	// TokenURL is the full URL to the token endpoint
	TokenURL string

	// Headers contains additional headers to include in token requests
	Headers map[string]string

	// GrantType specifies the OAuth grant type (defaults to "client_credentials")
	GrantType string

	MaxAttempts int

	JWKURL string

	JWKExpirationTime time.Duration
}

OAuthConfig contains the configuration for OAuth client credentials flow. It includes all necessary parameters for token endpoint authentication.

type RetryConfig

type RetryConfig struct {
	// MaxAttempts is the maximum number of retry attempts before giving up.
	// A value of 1 means no retries (only the initial attempt).
	MaxAttempts int

	// WaitTime is the duration to wait between retry attempts.
	// This helps prevent overwhelming the authorization server during issues.
	WaitTime time.Duration
}

RetryConfig defines parameters for retry behavior during token fetching. It allows customization of the retry mechanism to handle temporary failures and network issues gracefully.

type TokenCache

type TokenCache struct {
	// Token holds the current OAuth token
	Token string

	// ExpiresAt tracks the token's expiration time
	ExpiresAt time.Time

	// Config contains the OAuth configuration settings
	Config OAuthConfig

	JWTExpiresAt time.Time
	// contains filtered or unexported fields
}

TokenCache implements TokenProvider interface and handles caching of OAuth tokens. It provides automatic token refresh and retry logic collection. TokenCache is safe for concurrent use by multiple goroutines.

func NewTokenCache

func NewTokenCache(config OAuthConfig) *TokenCache

NewTokenCache creates a new TokenCache instance.

func (*TokenCache) FetchJWK

func (cache *TokenCache) FetchJWK(ctx context.Context) (jwk.Set, error)

FetchJWK fetches the JWK from Keycloak and caches it

func (*TokenCache) GetToken

func (cache *TokenCache) GetToken(ctx context.Context) (string, error)

GetToken handles getting, validating, and caching the JWT token. It implements a cache-first strategy, only fetching a new token when the cached token is expired or invalid.

The function is thread-safe and can be called concurrently. It uses the provided context for cancellation and timeout control.

func (*TokenCache) VerifyJWT

func (cache *TokenCache) VerifyJWT(ctx context.Context, jwtToken string) (jwt.Token, map[string]interface{}, error)

VerifyJWT validates a JWT token using the configured JWK set and returns the parsed token and claims.

This method performs the following steps: 1. Fetches the JWK set from the configured JWKURL (with caching) 2. Parses and validates the JWT token using the JWK set 3. Extracts both standard and private claims from the token

Standard claims extracted include:

  • sub (Subject)
  • iss (Issuer)
  • aud (Audience)
  • exp (Expiration Time)
  • nbf (Not Before)
  • iat (Issued At)
  • jti (JWT ID)

Parameters:

  • ctx: Context for the operation, which can be used for cancellation
  • jwtToken: The JWT token string to verify

Returns:

  • jwt.Token: The parsed JWT token object
  • map[string]interface{}: Combined map of standard and private claims
  • error: Any error that occurred during verification

The method will return an error if:

  • JWK set cannot be fetched
  • JWT token is invalid or malformed
  • Token signature verification fails
  • Token validation fails (e.g., expired token)

Jump to

Keyboard shortcuts

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