class KeyVault::ManagedIdentityAuth

Authenticator for Azure Key Vault using Managed Identity

Public Class Methods

new(api_version: METADATA_API_VERSION) click to toggle source

Create authenticator using Managed Identity

Parameters:

api_version

(optional) Version of the azure Metadata REST API to use. Defaults to METADATA_API_VERSION

# File lib/key_vault/managed_identity_auth.rb, line 10
def initialize(api_version: METADATA_API_VERSION)
  @api_version = api_version || METADATA_API_VERSION
end

Public Instance Methods

bearer_token() click to toggle source

Authenticates with Azure using OAUTH 2.0

Returns:

A string containing the bearer token for insertion into request headers

Raises:

ArgumentError

If the authentication request format is invalid

KeyVault::Unauthorized

If authentication fails authorization

# File lib/key_vault/managed_identity_auth.rb, line 20
def bearer_token
  result = RestClient::Request.execute(method: :get,
                                       url: url,
                                       headers: headers)
  token_resp = JSON.parse(result)
  "Bearer #{token_resp['access_token']}"
rescue RestClient::BadRequest
  raise ArgumentError, 'Could not authenticate to Azure (Bad Request)'
rescue RestClient::Unauthorized
  raise KeyVault::Unauthorized
end

Private Instance Methods

headers() click to toggle source
# File lib/key_vault/managed_identity_auth.rb, line 34
def headers
  { 'Metadata' => 'true' }
end
url() click to toggle source
# File lib/key_vault/managed_identity_auth.rb, line 38
def url
  "http://169.254.169.254/metadata/identity/oauth2/token?api-version=#{@api_version}&resource=https://vault.azure.net"
end