locked
How to retrieve secret from Azure Key Vault RRS feed

  • Question

  • User-1035489207 posted

    I am trying to convert the example code at https://docs.microsoft.com/en-us/azure/key-vault/tutorial-net-create-vault-azure-web-app to VB.net and use it to access a secret that I have stored in my Azure Key Vault. I used the converter at http://converter.telerik.com/.

    The converted code gives an error saying "Delegate 'KeyVaultClient.AuthenticationCallback' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor."

    This is the converted code:

    Imports Microsoft.Azure.KeyVault
    Imports Microsoft.Azure.Services.AppAuthentication
    Imports Microsoft.Azure.KeyVault.Models
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Dim azureServiceTokenProvider As AzureServiceTokenProvider = New AzureServiceTokenProvider
    
            Dim keyVaultClient As KeyVaultClient = New KeyVaultClient(New KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback))
            Dim secret As String = keyVaultClient.GetSecretAsync("https://<YourKeyVaultName>.vault.azure.net/secrets/AppSecret").ConfigureAwait(False)
            TextBox1.Text = secret.Value
    
        End Sub

    I would like to know the code necessary to access a secret in my key vault. I have given my app all permissions to access the vault in the Azure portal and I am logged in with my Azure account in VS2017 and I have been at this for 3 days and cannot find any VB examples for accessing key vault that are current.

    Sunday, July 21, 2019 10:37 PM

All replies

  • User283571144 posted

    Hi JamberFX,

    According to your description, I suggest you could use GetAccessTokenAsync instead of the azureServiceTokenProvider to get the access token.

    More details, you could refer to below codes:

    Imports System.Threading.Tasks
    Imports Microsoft.Azure.KeyVault
    Imports Microsoft.Azure.KeyVault.Models
    Imports Microsoft.Azure.Services.AppAuthentication
    Imports Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider
    
    Public Class AzureKVTest
        Inherits System.Web.UI.Page
    
        Public Property Message As String
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            Message = "Your application description page."
            Dim retries As Integer = 0
            Dim retry As Boolean = False
    
            Try
                Dim azureServiceTokenProvider As AzureServiceTokenProvider = New AzureServiceTokenProvider()
    
                Dim keyVaultClient As KeyVaultClient = New KeyVaultClient(New KeyVaultClient.AuthenticationCallback(AddressOf GetAccessTokenAsync))
                Dim secret = keyVaultClient.GetSecretAsync("https://<keyvaluename>.vault.azure.net/secrets/AppSecret111").Result
                Message = secret.Value
            Catch keyVaultException As KeyVaultErrorException
                Message = keyVaultException.Message
            End Try
    
    
    
        End Sub
    
        Private Shared Function getWaitTime(ByVal retryCount As Integer) As Long
            Dim waitTime As Long = (CLng(Math.Pow(2, retryCount)) * 100L)
            Return waitTime
        End Function
    
        Public Async Function GetAccessTokenAsync() As Task(Of String)
            Dim azureServiceTokenProvider = New AzureServiceTokenProvider()
            Dim accessToken As String = Await azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net")
            Return accessToken
        End Function
    End Class

    Result:

    Best Regards,

    Brando

    Monday, July 22, 2019 5:09 AM
  • User-1035489207 posted

    Awesome!  Thank you Brando.  I am still having one problem with the code though.  I get a "Forbidden" response.  I have setup the key vault with all of the permissions that I can find that give my web app and my Azure Account access but I still get the "Forbidden" error shown below.  Can you tell me the permissions necessary to make this work?  Also, I am currently running it in debug mode on my local machine.  I need for it to be able to access the secrets regardless of whether debugging locally or deployed on Azure as a Web App.  I am logged on to my Azure Account in VS 2017 on my local machine and the key vault is in the same resource group as my web app on Azure.

    Error

    I also tried changing the url shown in GetAccessTokenAsync Function and get the following error.  I am assuming that I don't have MSI setup correctly.  I am going to mess with it and see if I can get it right.  Do you have any advice base don these errors?

    Monday, July 22, 2019 3:03 PM
  • User283571144 posted

    Hi JamberFX,

    According to your description, I guess you may not have the enough permission to access the key valut in visual studio.

    I suggest you could go to azure portal to access the azure KV policies and make sure you have enough permission on get and list for the azure user account(email).

    Then you could open the visual studio and make sure you have login in the user with the azure portal Email.

    Best Regards,

    Brando

    Tuesday, July 23, 2019 6:24 AM
  • User-1035489207 posted

    Hi Brando,

    I checked the permissions and I have Get and List permissions for both my web app and my user account.  I have tried a few different things with assigning MSI through the Azure CLI but I can't seem to find the permission that I am missing that is preventing access.  Below is the most current error that I received:

    "

    AzureServiceTokenProviderException: Parameters: Connection String: [No connection string specified], Resource: https://XXXXXXXvault.vault.azure.net/, Authority: . Exception Message: Tried the following 4 methods to get an access token, but none of them worked.

    Parameters: Connection String: [No connection string specified], Resource: https://XXXXXXXvault.vault.azure.net/, Authority: . Exception Message: Tried to get token using Managed Service Identity. Unable to connect to the Managed Service Identity (MSI) endpoint. Please check that you are running on an Azure resource that has MSI setup.

    Parameters: Connection String: [No connection string specified], Resource: https://XXXXXXXvault.vault.azure.net/, Authority: . Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. 

    Exception for Visual Studio token provider Microsoft.Asal.TokenService.exe : TS003: Error, TS004: Unable to get access token.  'Failed to refresh access token'

     

    Parameters: Connection String: [No connection string specified], Resource: https://XXXXXXXvault.vault.azure.net/, Authority: . Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. ERROR: The command failed with an unexpected error. Here is the traceback:

    ERROR: Get Token request returned http error: 400 and server response: {"error":"invalid_resource","error_description":"AADSTS500011: The resource principal named https://XXXXXXXvault.vault.azure.net/ was not found in the tenant named b07e77bc-ce14-4ec5-bc6c-5024da128fca. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.\r\nTrace ID: 78 XXXXXXX 2ee7b6ce0300\r\nCorrelation ID: acfe0e30 XXXXXXX 4f07\r\nTimestamp: 2019-07-23 15:02:18Z","error_codes":[500011],"timestamp":"2019-07-23 15:02:18Z","trace_id":"785342d XXXXXXX e7b6ce0300","correlation_id":"acfe XXXXXXX f07"}

    Traceback (most recent call last):

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\knack\knack\cli.py", line 206, in invoke

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\azure-cli-core\azure\cli\core\commands\__init__.py", line 578, in execute

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\azure-cli-core\azure\cli\core\commands\__init__.py", line 636, in _run_jobs_serially

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\azure-cli-core\azure\cli\core\commands\__init__.py", line 629, in _run_job

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\six\six.py", line 693, in reraise

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\azure-cli-core\azure\cli\core\commands\__init__.py", line 606, in _run_job

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\azure-cli-core\azure\cli\core\commands\__init__.py", line 305, in __call__

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\azure-cli-core\azure\cli\core\__init__.py", line 485, in default_command_handler

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\azure-cli\azure\cli\command_modules\profile\custom.py", line 61, in get_access_token

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\azure-cli-core\azure\cli\core\_profile.py", line 604, in get_raw_token

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\azure-cli-core\azure\cli\core\_profile.py", line 913, in retrieve_token_for_user

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\authentication_context.py", line 145, in acquire_token

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\authentication_context.py", line 128, in _acquire_token

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\authentication_context.py", line 143, in token_func

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\token_request.py", line 347, in get_token_from_cache_with_refresh

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\token_request.py", line 127, in _find_token_from_cache

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\cache_driver.py", line 199, in find

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\cache_driver.py", line 184, in _refresh_entry_if_necessary

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\cache_driver.py", line 160, in _acquire_new_token_from_mrrt

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\token_request.py", line 137, in _get_token_with_token_response

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\token_request.py", line 339, in _get_token_with_refresh_token

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\token_request.py", line 112, in _oauth_get_token

      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-qdpilz60\adal\adal\oauth2_client.py", line 289, in get_token

    adal.adal_error.AdalError: Get Token request returned http error: 400 and server response: {"error":"invalid_resource","error_description":"AADSTS500011: The resource principal named https://XXXXXXXvault.vault.azure.net/ was not found in the tenant named b07e77bc-ce14-4ec5-bc6c-5024da128fca. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.\r\nTrace ID: 785342d3-80a8-416c-a7b9-2ee7b6ce0300\r\nCorrelation ID: acfe0e30- XXXXXXX 04f07\r\nTimestamp: 2019-07-23 15:02:18Z","error_codes":[500011],"timestamp":"2019-07-23 15:02:18Z","trace_id":"785342d3-XXXXXXX7b6ce0300","correlation_id":"acfe0 XXXXXXX a90c04f07"}

    WARNING: 

    To open an issue, please run: 'az feedback'

     

    Parameters: Connection String: [No connection string specified], Resource: https://XXXXXvault.vault.azure.net/, Authority: https://login.microsoftonline.com/common. Exception Message: Tried to get token using Active Directory Integrated Authentication. Access token could not be acquired. Failed to get user name from the operating system.Inner Exception : No mapping between account names and security IDs was done

     

    <div>"</div> <div></div> <div>And this is what my current code looks like:</div> <div></div> <div>

    Imports System.Threading.Tasks
    Imports Microsoft.Azure.KeyVault
    Imports Microsoft.Azure.KeyVault.Models
    Imports Microsoft.Azure.Services.AppAuthentication
    Imports Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider
    
    Public Class SocialXXXXX
    	Inherits System.Web.UI.Page
    
    	Public Property Message As String
    
    	Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
    
    		Dim retries As Integer = 0
    		Dim retry As Boolean = False
    
    		Try
    			Dim azureServiceTokenProvider As AzureServiceTokenProvider = New AzureServiceTokenProvider()
    
    			Dim keyVaultClient As KeyVaultClient = New KeyVaultClient(New KeyVaultClient.AuthenticationCallback(AddressOf GetAccessTokenAsync))
    			Dim secret = keyVaultClient.GetSecretAsync("https://XXXXXvault.vault.azure.net/secrets/ExamplePassword/52ec77ddc2d96c63f6c9").Result
    			TextBox7.Text = secret.Value
    		Catch keyVaultException As KeyVaultErrorException
    			TextBox7.Text = keyVaultException.Message
    		End Try
    
    
    
    	End Sub
    
    	Private Shared Function getWaitTime(ByVal retryCount As Integer) As Long
    		Dim waitTime As Long = (CLng(Math.Pow(2, retryCount)) * 100L)
    		Return waitTime
    	End Function
    
    	Public Async Function GetAccessTokenAsync() As Task(Of String)
    		Dim azureServiceTokenProvider = New AzureServiceTokenProvider()
    		Dim accessToken As String = Await azureServiceTokenProvider.GetAccessTokenAsync("https://XXXXXvault.vault.azure.net/")
    		Return accessToken
    	End Function

    </div>

    Tuesday, July 23, 2019 3:12 PM
  • User283571144 posted

    Hi JamberFX,

    I have replied the the issue on your other thread to suggest you could try to use AAD registered application to achieve your requirement.

    Best Regards,

    Brando

    Friday, July 26, 2019 1:48 AM
  • User-1035489207 posted

    Thank you Brando,  I am traveling currently and am unable to work on this.   However, I will give it a go as soon as possible.

    Friday, July 26, 2019 8:58 AM
  • User-60226315 posted

    Hello,

    I am having the same issue.  What is the url to the other thread you are mentioning?

    Thanks

    Monday, March 30, 2020 7:17 PM