Class: Oauth2ApiClient::TokenProvider

Inherits:
Object
  • Object
show all
Defined in:
lib/oauth2_api_client/token_provider.rb

Overview

The TokenProvider class is responsible for obtaining and caching an oauth2 token, when client id, client secret and token url is given.

Examples:

Oauth2ApiClient::TokenProvider.new(
  client_id: "client id",
  client_secret: "client secret",
  token_url: "https://auth.example.com/oauth2/token",
  cache: Rails.cache, # optional
  max_token_ttl: 1800 # optional
)

Instance Method Summary collapse

Constructor Details

#initialize(client_id:, client_secret:, token_url:, cache: ActiveSupport::Cache::MemoryStore.new, max_token_ttl: 3600) ⇒ TokenProvider

Creates a new TokenProvider instance.

Examples:

Oauth2ApiClient::TokenProvider.new(
  client_id: "client id",
  client_secret: "client secret",
  token_url: "https://auth.example.com/oauth2/token",
)

Parameters:

  • client_id (String)

    The client id

  • client_secret (String)

    The client secret

  • token_url (String)

    The oauth2 endpoint for generating tokens

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

    An ActiveSupport compatible cache implementation. Defaults to ‘ActiveSupport::Cache::MemoryStore.new`

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

    A maximum token lifetime. Defaults to 3600



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/oauth2_api_client/token_provider.rb', line 33

def initialize(client_id:, client_secret:, token_url:, cache: ActiveSupport::Cache::MemoryStore.new, max_token_ttl: 3600)
  @client_id = client_id
  @client_secret = client_secret
  @token_url = token_url
  @max_token_ttl = max_token_ttl
  @cache = cache

  oauth_uri = URI.parse(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

#invalidate_tokenString

Invalidates the cached token, i.e. removes it from the cache

Returns:

  • (String)

    the token



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

def invalidate_token
  @cache.delete(cache_key)
end

#tokenString

Returns the oauth2 token, either from the cache, or newly generated

Returns:

  • (String)

    the token



54
55
56
57
58
# File 'lib/oauth2_api_client/token_provider.rb', line 54

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