Class: Oauth2ApiClient

Inherits:
Object
  • Object
show all
Defined in:
lib/oauth2_api_client.rb,
lib/oauth2_api_client/version.rb,
lib/oauth2_api_client/http_error.rb

Overview

The Oauth2ApiClient class is a client wrapped around the oauth2 and http-rb gem to interact with APIs using oauth2 for authentication with automatic token caching and renewal.

Defined Under Namespace

Classes: HttpError

Constant Summary collapse

VERSION =
"1.0.0"

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, client_id:, client_secret:, oauth_token_url:, cache: ActiveSupport::Cache::MemoryStore.new, max_token_ttl: 3600, base_request: HTTP) ⇒ Oauth2ApiClient

Creates a new Oauth2ApiClient

Examples:

client = Oauth2ApiClient.new(
  base_url: "https://api.example.com/",
  client_id: "the client id",
  client_secret: "the client secret",
  oauth_token_url: "https://auth.example.com/oauth2/token",
  cache: Rails.cache,
  base_request: HTTP.headers("User-Agent" => "API client")
)

client.post("/orders", json: { address: "..." }).status.success?
client.headers("User-Agent" => "API Client").timeout(read: 5, write: 5).get("/orders").parse

Parameters:

  • base_url (String)

    The base url of the API to interact with

  • client_id (String)

    The client id to use for oauth2 authentication

  • client_secret (String)

    The client secret to use for oauth2 authentication

  • oauth_token_url (String)

    The url to obtain tokens from

  • cache (defaults to: ActiveSupport::Cache::MemoryStore.new)

    The cache instance to cache the tokens, e.g. `Rails.cache`. Defaults to `ActiveSupport::Cache::MemoryStore.new`

  • max_token_ttl (#to_i) (defaults to: 3600)

    The max lifetime of the token in the cache

  • base_request (defaults to: HTTP)

    You can pass some http-rb rqeuest as the base. Useful, if some information needs to be passed with every request. Defaults to `HTTP`


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/oauth2_api_client.rb', line 41

def initialize(base_url:, client_id:, client_secret:, oauth_token_url:, cache: ActiveSupport::Cache::MemoryStore.new, max_token_ttl: 3600, base_request: HTTP)
  @base_url = base_url
  @client_id = client_id
  @client_secret = client_secret
  @oauth_token_url = oauth_token_url
  @max_token_ttl = max_token_ttl
  @cache = cache
  @request = base_request

  oauth_uri = URI.parse(oauth_token_url)

  @oauth_client = OAuth2::Client.new(
    @client_id,
    @client_secret,
    site: URI.parse("#{oauth_uri.scheme}://#{oauth_uri.host}:#{oauth_uri.port}/").to_s,
    token_url: oauth_uri.path
  )
end

Instance Method Details

#tokenString

Returns a oauth2 token to use for authentication

Returns:

  • (String)

    The token


64
65
66
67
68
# File 'lib/oauth2_api_client.rb', line 64

def token
  @cache.fetch(cache_key, expires_in: @max_token_ttl.to_i) do
    @oauth_client.client_credentials.get_token.token
  end
end