Class: IBM::Cloud::SDKHTTP::IAMToken

Inherits:
Object
  • Object
show all
Includes:
BaseHTTPMixin
Defined in:
lib/ibm/cloud/sdk_http/iam_token.rb

Overview

Used to authenticate with IAM.

Instance Attribute Summary collapse

Attributes included from BaseHTTPMixin

#endpoint

Instance Method Summary collapse

Methods included from BaseHTTPMixin

#adhoc, #delete, #get, #metadata, #patch, #post, #put, #unchecked_response, #url

Constructor Details

#initialize(api_key, connection, logger: nil) ⇒ IAMToken

Returns a new instance of IAMToken.



11
12
13
14
15
16
17
# File 'lib/ibm/cloud/sdk_http/iam_token.rb', line 11

def initialize(api_key, connection, logger: nil)
  @api_key = api_key
  @logger = logger
  @connection = connection
  @response = nil
  @data = nil
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



19
20
21
# File 'lib/ibm/cloud/sdk_http/iam_token.rb', line 19

def connection
  @connection
end

#responseObject (readonly)

Returns the value of attribute response.



19
20
21
# File 'lib/ibm/cloud/sdk_http/iam_token.rb', line 19

def response
  @response
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:

  • (IBM::Cloud::SDK::VPC::Exceptions::HttpStatusError)

    Response code is not either in 200-series or 404.



46
47
48
49
# File 'lib/ibm/cloud/sdk_http/iam_token.rb', line 46

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

#dataObject



31
32
33
34
# File 'lib/ibm/cloud/sdk_http/iam_token.rb', line 31

def data
  fetch unless @response
  @response.raise_for_status!.json
end

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

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

Returns:

  • (IBM::Cloud::SDK::VPC::Response)

    Wrapped response to query.

Raises:

  • (IBM::Cloud::SDK::VPC::Exceptions::HttpStatusError)

    Response code is not either in 200-series or 404.



39
40
41
# File 'lib/ibm/cloud/sdk_http/iam_token.rb', line 39

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

#fetchObject



21
22
23
24
25
26
27
28
29
# File 'lib/ibm/cloud/sdk_http/iam_token.rb', line 21

def fetch
  payload = {
    body: {
      grant_type: 'urn:ibm:params:oauth:grant-type:apikey',
      apikey: @api_key
    }
  }
  @response = @connection.request('post', 'https://iam.cloud.ibm.com/identity/token', payload)
end