Class: Kessel::Auth::OAuth2ClientCredentials

Inherits:
Object
  • Object
show all
Includes:
Kessel::Auth
Defined in:
lib/kessel/auth.rb

Overview

OpenID Connect Client Credentials flow implementation using discovery.

This provides a secure OIDC Client Credentials flow implementation with automatic endpoint discovery. Works seamlessly with OIDC-compliant providers that support discovery.

Examples:

oauth = OAuth2ClientCredentials.new(
  client_id: 'kessel-client',
  client_secret: 'super-secret-key',
  token_endpoint: 'https://my-domain/auth/realms/my-realm/protocol/openid-connect/token'
)

# Get current access token (automatically cached and refreshed)
token = oauth.get_token

Since:

  • 1.0.0

Constant Summary

Constants included from Kessel::Auth

DEFAULT_EXPIRES_IN, EXPIRATION_WINDOW

Instance Method Summary collapse

Methods included from Kessel::Auth

#fetch_oidc_discovery, #oauth2_auth_request

Constructor Details

#initialize(client_id:, client_secret:, token_endpoint:) ⇒ OAuth2ClientCredentials

Creates a new OIDC client with specified token endpoint.

Examples:

oauth = OAuth2ClientCredentials.new(
  client_id: 'my-app',
  client_secret: 'secret',
  token_endpoint: 'https://my-domain/auth/realms/my-realm/protocol/openid-connect/token'
)

Parameters:

  • client_id (String)

    OIDC client identifier

  • client_secret (String)

    OIDC client secret

  • token_endpoint (String)

    OIDC token endpoint URL

Raises:

Since:

  • 1.0.0



126
127
128
129
130
131
132
133
# File 'lib/kessel/auth.rb', line 126

def initialize(client_id:, client_secret:, token_endpoint:)
  check_dependencies!

  @client_id = client_id
  @client_secret = client_secret
  @token_endpoint = token_endpoint
  @token_mutex = Mutex.new
end

Instance Method Details

#get_token(force_refresh: false) ⇒ RefreshTokenResponse

Gets the current access token with automatic caching and refresh.

Uses OIDC Client Credentials flow with automatic token caching, expiration checking, and refresh logic.

Examples:

token = oauth.get_token
# Use token in Authorization header: "Bearer #{token}"

Returns:

Raises:

Since:

  • 1.0.0



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/kessel/auth.rb', line 146

def get_token(force_refresh: false)
  return @cached_token if !force_refresh && token_valid?

  @token_mutex.synchronize do
    @cached_token = nil if force_refresh

    # Double-check: another thread might have refreshed the token
    return @cached_token if token_valid?

    @cached_token = refresh

    return @cached_token
  rescue StandardError => e
    raise OAuthAuthenticationError, "Failed to obtain client credentials token: #{e.message}"
  end
end