Class: X::AppOnlyAuthenticator

Inherits:
Authenticator show all
Defined in:
x-core/lib/x/core/app_only_authenticator.rb

Overview

Authenticates as an app with a bearer token, fetched with the API key and secret when first needed

A bearer token the API rejects with 401 Unauthorized, as it does one that was invalidated, is dropped, and the request is sent again with one fetched in its place.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key:, api_key_secret:, bearer_token: nil) ⇒ AppOnlyAuthenticator

Initialize a new app-only authenticator

Examples:

Create an app-only authenticator

X::AppOnlyAuthenticator.new(api_key: "key", api_key_secret: "secret")

Parameters:

  • api_key (String) —

    the API key

  • api_key_secret (String) —

    the API key secret

  • bearer_token (String, nil) (defaults to: nil) —

    a bearer token already fetched with these credentials

Raises:

  • (ArgumentError) —

    if the API key or secret is nil or empty, or the bearer token is empty



45
46
47
48
49
50
51
52
# File 'x-core/lib/x/core/app_only_authenticator.rb', line 45

def initialize(api_key:, api_key_secret:, bearer_token: nil)
  CredentialValidator.validate_required!({api_key:, api_key_secret:}, {bearer_token:})
  @api_key = api_key
  @api_key_secret = api_key_secret
  @bearer_token = bearer_token
  @connection, @token_url, @token_headers = Connection.new, TOKEN_URL, {}
  @mutex = Mutex.new
end

Instance Attribute Details

#api_key ⇒ String (readonly)

The API key

Examples:

Get the API key

authenticator.api_key

Returns:

  • (String) —

    the API key



33
34
35
# File 'x-core/lib/x/core/app_only_authenticator.rb', line 33

def api_key
  @api_key
end

Instance Method Details

#headers(_request) ⇒ Hash{String => String}

Generate the authentication headers, fetching the bearer token first if needed

Examples:

Generate the header

authenticator.headers(request) # => {"Authorization" => "Bearer ..."}

Parameters:

  • _request (#http_method, #uri, #body, #[], nil) —

    the request, which app-only authentication does not sign

Returns:

  • (Hash{String => String}) —

    the authorization header

Raises:

  • (AuthorizationError) —

    if X refuses to issue the bearer token

  • (HTTPError, InvalidResponse) —

    if the token endpoint limits the rate of the request or fails to answer, as a server error, a redirect, or the page of a proxy says



64
65
66
# File 'x-core/lib/x/core/app_only_authenticator.rb', line 64

def headers(_request)
  {AUTHENTICATION_HEADER => "Bearer #{bearer_token}"}
end