Azure / azure-storage-ruby

Microsoft Azure Storage Library for Ruby
http://azure.github.io/azure-storage-ruby/
84 stars 150 forks source link

Authenticating with Azure AD credentials? #213

Open KNejad opened 2 years ago

KNejad commented 2 years ago

Is it possible to authenticate with Active Directory credentials?

I've been trying to work out how to do this but haven't had any luck yet.

This PR seems to add support for it, but it's not documented how to use it anywhere: https://github.com/Azure/azure-storage-ruby/pull/153

I tried copying the code from the test, which uses ADAL, but the gem doesn't seem to install properly because the ADAL gem seems to be dead and bugged: https://github.com/AzureAD/azure-activedirectory-library-for-ruby/issues/44

Is there any other way to authenticate using AD credentials?

drewda commented 1 year ago

This was a very frustrating experience, but I believe I have now gotten this to work using the following:

# Gemfile
gem 'azure-storage-common'
gem 'azure-storage-blob'
gem 'adal', github: 'AzureAD/azure-activedirectory-library-for-ruby', ref: '24e1b7f0dc374dcb968171f80e832118691d288c'

def azure_token_signer
  tenant_id = ENV.fetch("AZURE_TENANT_ID", nil)
  client_id = ENV.fetch("AZURE_CLIENT_ID", nil)
  client_secret = ENV.fetch("AZURE_CLIENT_SECRET", nil)

  if tenant_id.nil? || client_id.nil? || client_secret.nil?
    raise "Azure ActiveDirectory credentials not provided"
  end

  auth_ctx = ADAL::AuthenticationContext.new("login.microsoftonline.com", tenant_id)
  client_cred = ADAL::ClientCredential.new(client_id, client_secret)
  token = auth_ctx.acquire_token_for_client("https://storage.azure.com/", client_cred)
  access_token = token.access_token

  token_credential = Azure::Storage::Common::Core::TokenCredential.new access_token
  Azure::Storage::Common::Core::Auth::TokenSigner.new token_credential
end

def storage_common_client
  Azure::Storage::Common::Client::create(storage_account_name: ENV['AZURE_STORAGE_ACCOUNT'], signer: self.azure_token_signer)
end

def blob_service_client
  Azure::Storage::Blob::BlobService.new(api_version: "2018-11-09", client: storage_common_client)
end