Class: IBM::Cloud::SDK::VPC::Token

Inherits:
Object
  • Object
show all
Defined in:
lib/ibm/cloud/sdk/vpc/helpers/connection.rb

Overview

The IAM token manager.

Instance Method Summary collapse

Constructor Details

#initialize(api_key, logger: nil, client: nil) ⇒ Token

Returns a new instance of Token.



56
57
58
59
60
61
# File 'lib/ibm/cloud/sdk/vpc/helpers/connection.rb', line 56

def initialize(api_key, logger: nil, client: nil)
  @api_key = api_key
  @logger = logger
  @client = client
  @data = fetch
end

Instance Method Details

#authorization_headerString

Get a Bearer token string. Before returning check to see if token is expired.

Returns:

  • (String)

    The Bearer token header used in subsequent requests.

Raises:



88
89
90
91
# File 'lib/ibm/cloud/sdk/vpc/helpers/connection.rb', line 88

def authorization_header
  fetch if expired?
  "#{@data.fetch(:token_type)} #{@data.fetch(:access_token)}"
end

#expired?IBM::Cloud::SDK::VPC::Response

Check to see if the access_token is expired. Fetch a new token if none exists.

Returns:

Raises:



80
81
82
83
# File 'lib/ibm/cloud/sdk/vpc/helpers/connection.rb', line 80

def expired?
  fetch unless @data
  @data.fetch(:expiration).to_i <= Time.now.to_i + 600
end

#fetchIBM::Cloud::SDK::VPC::Response

Retrieve a new access_token from IAM.

Returns:

Raises:



66
67
68
69
70
71
72
73
74
75
# File 'lib/ibm/cloud/sdk/vpc/helpers/connection.rb', line 66

def fetch
  payload = {
    form: {
      grant_type: 'urn:ibm:params:oauth:grant-type:apikey',
      apikey: @api_key
    }
  }
  response = HTTP.post('https://iam.cloud.ibm.com/identity/token', payload)
  @data = Response.new(response).raise_for_status?.json
end