question

NikitaPandey-6512 avatar image
0 Votes"
NikitaPandey-6512 asked ·

Azure key vault

I have created a web application in c#.net to access the key vault from azure without using credentials in the code, but I am facing one issue.

Question
Sign in to vote
0
Sign in to vote
I have created the web application in c#.net but I am getting the following error:-

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException: Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/66375204-7fc7-4ceb-be15-a5b6ea7b6ef6. 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://vault.azure.net, Authority: https://login.windows.net/66375204-7fc7-4ceb-be15-a5b6ea7b6ef6. Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. An error occurred while sending the request.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/66375204-7fc7-4ceb-be15-a5b6ea7b6ef6. Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Visual Studio Token provider file not found at "C:\Windows\system32\config\systemprofile\AppData\Local.IdentityService\AzureServiceAuth\tokenprovider.json"
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/66375204-7fc7-4ceb-be15-a5b6ea7b6ef6. Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\runpy.py", line 193, in run_module_as_main
"
main", mod_spec)
File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\runpy.py", line 85, in run_code
exec(code, run_globals)
File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\azure-cli\azure\cli_main
.py", line 33, in <module>
File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\azure-cli-core\azure\cli\core_init
.py", line 547, in get_default_cli
File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\azure-cli-core\azure\cli\core\azlogging.py", line 30, in <module>
File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\azure-cli-core\azure\cli\core\commands_init.py", line 28, in <module>
File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\azure-cli-core\azure\cli\core\extension_init
.py", line 16, in <module>
File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\knack\knack\config.py", line 39, in init
File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\knack\knack\util.py", line 108, in ensure_dir
File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\knack\knack\util.py", line 105, in ensure_dir
File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\os.py", line 220, in makedirs
mkdir(name, mode)
PermissionError: [WinError 5] Access is denied: 'C:\\Windows\\system32\\config\\systemprofile\.azure'

Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/66375204-7fc7-4ceb-be15-a5b6ea7b6ef6. Exception Message: Tried to get token using Active Directory Integrated Authentication. Access token could not be acquired. Integrated Windows Auth is not supported for managed users. See https://aka.ms/adal-iwa for details.



The following is the code snippet:-

using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Services.AppAuthentication;
using SummitSecurity;
using System;
using System.Configuration;
using System.Threading.Tasks;


namespace Azure_WebApp
{
public partial class Azure_Form : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

     protected void Button1_Click(object sender, EventArgs e)
     {
         string str =ResultOnGetAsync().Result;
         Label1.Text = str.ToString();
 }
     public static string WMIUserPWDKey = string.Empty;

     public static string Message { get; set; }
     private static async Task<string> ResultOnGetAsync()
     {
         string ret = string.Empty;

         try
         {
             AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();

             KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
             var secret = await keyVaultClient.GetSecretAsync("https://summitazurekey.vault.azure.net/secrets/AzureKey")
                     .ConfigureAwait(false);

             Message = secret.Value;
             WMIUserPWDKey = fnDecrypt(secret.Tags["WMIUserPWDKey"].ToString(), "");
             string StrToEncryptAndDecrypt = "TestStringToEncryptAndDecrypt";
             string strEncrypted = string.Empty;
             strEncrypted = CommonExtensionMethods.QueryStringEncrypt(StrToEncryptAndDecrypt, WMIUserPWDKey);
             ret = $"AzureDecryptKey is {WMIUserPWDKey.ToString()}\n" +
                          "" +
                          $"{Encrypted()}";

         }
         catch(Exception ex)
         {

             Console.WriteLine(ex.ToString());
         }
         return ret;

     }
     static string Encrypted()
     {
         string StrToEncryptAndDecrypt = "TestStringToEncryptAndDecrypt";
         string strEncrypted = string.Empty;
         strEncrypted = CommonExtensionMethods.QueryStringEncrypt(StrToEncryptAndDecrypt, WMIUserPWDKey);
         string strDecrypted = string.Empty;
         strDecrypted = CommonExtensionMethods.QueryStringDecrypt(strEncrypted, WMIUserPWDKey);
         string EnDecKey = $"Encrypted: " +
                     $"{strEncrypted.ToString()}\n" + "Decrypted: " +
                     $"{strDecrypted.ToString()}";
         return EnDecKey;
     }

     // This method implements exponential backoff if there are 429 errors from Azure Key Vault
     private static long getWaitTime(int retryCount)
     {
         long waitTime = ((long)Math.Pow(2, retryCount) * 100L);
         return waitTime;
     }

     // This method fetches a token from Azure Active Directory, which can then be provided to Azure Key Vault to authenticate
     public async Task<string> GetAccessTokenAsync()
     {
         var azureServiceTokenProvider = new AzureServiceTokenProvider();
         string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://summitazurekey.vault.azure.net");
         return accessToken;
     }

Please me help out, why i am not able to access secret from vault, as in console it is working fine, but in asp.net web app it is not working.

azure-active-directory
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

saurabhsh-msft avatar image
0 Votes"
saurabhsh-msft answered ·

I tried your code and it worked fine for me on my local development environment.
Can you please check if you have selected the correct Account under Azure Service Authentication in your Visual Studio. (Go to Visual Studio and Tools > Options).

6831-visualstudioauthentication.png

Basically, when you run code in your local the AppAuthentication library uses your developer credentials to connect to run your local development environment and fetches tokens either using Visual Studio, Azure CLI or Azure AD Authentication. If none of options works then you get the error you have posted in your question. Please refer to Local development authentication for details.

However, if you are planning to deploy your web application to Azure then I suggest you to use manage identity to authenticate Azure Key Vault. Please refer to below documentation/sample for details :



· 1 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I have done this what you told again it is not working for me. I am using the same account in both azure and visual studio.

0 Votes 0 · ·
PiyushMutha avatar image
0 Votes"
PiyushMutha answered ·

I guess you've not added your App Service to your Key Vault's Access Policies. In that case,

  1. Navigate to the Key Vault resource in Azure Portal.

  2. I the menu, find Access Policies button and click on that.

  3. On the Access Policies page, find +Add Access Policy link and click.

  4. On the Add access policy page, Select all the permissions you want to grant to your App Service(probably all if you want to test this solution) and click on Select Principal

  5. In the principal window, search for your App Service using the App Service Name and Select.

  6. On the Add access policy page, click Add to add the policy to your Key Vault.

  7. Finally on the Access Policies page, click "Save" to save your changes. (a lot of people miss this step)

Restart your App Service and the underlying WebJobs (if any), that should solve your problem

· 2 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

i have given the access in the Azure Portal for my App service again, it is working properly.
Please help me out I am stuck from last 2 days.

0 Votes 0 · ·
PiyushMutha avatar image PiyushMutha NikitaPandey-6512 ·

Try this out...

Pass “RunAs=App;” in the connectionString parameter of AzureServiceTokenProvider. This way it will not try different modes to obtain a token.

0 Votes 0 · ·
VarunSharma-5683 avatar image
0 Votes"
VarunSharma-5683 answered ·

Is this deployed using IIS? It seems like that based on the error. Normally VS token provider file is in the current user's profile, but it is looking at a different location here, as per exception: "Visual Studio Token provider file not found at "C:\Windows*system32\config"*

If deployed using IIS, please see this to resolve:
https://docs.microsoft.com/en-us/azure/key-vault/service-to-service-authentication#cant-retrieve-tokens-when-debugging-app-in-iis

In general, it is easier to do local development using IIS Express, since it uses current user's user profile.

· 1 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Yes it is hosted on IIS. But I don't know why this issue coming and now I am facing the following error:-

Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/66375204-7fc7-4ceb-be15-a5b6ea7b6ef6. 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://vault.azure.net, Authority: https://login.windows.net/66375204-7fc7-4ceb-be15-a5b6ea7b6ef6. Exception Message: Tried to get token using Active Directory Integrated Authentication. Access token could not be acquired. Integrated Windows Auth is not supported for managed users. See https://aka.ms/adal-iwa for details.

Please help me out, I don't know why my web app is not working.

0 Votes 0 · ·
VarunSharma-5683 avatar image
0 Votes"
VarunSharma-5683 answered ·

Can you please share more details about what you did to fix the issue? Did you try the link I had shared for running this in IIS?

Also, can you please share the entire error message? In the most recent error message you shared, it only shows the error for Integrated Windows auth. Thanks!

· 2 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Yes I tried with Link which you shared, but still it is not working. It is working if we run using iis express, but not working if we host on iis.. Why? since app will be hosted on iis only.. ​ it is only due to some permission issue..
The following is the error message:-

Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/66375204-7fc7-4ceb-be15-a5b6ea7b6ef6. 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://vault.azure.net, Authority: https://login.windows.net/66375204-7fc7-4ceb-be15-a5b6ea7b6ef6. Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. An error occurred while sending the request.



0 Votes 0 · ·

When you host the app on Azure, azureServiceTokenProvider will automatically use managed identity. The purpose of the library is to use managed identity on Azure. So you can develop locally and use IIS Express and use your own identity for local development. When you deploy to Azure, it will switch to using managed identity. Please see this https://docs.microsoft.com/en-us/azure/key-vault/tutorial-net-create-vault-azure-web-app



0 Votes 0 · ·
SaurabhSharma-msft avatar image
1 Vote"
SaurabhSharma-msft answered ·

@NikitaPandey-6512 When you are running you web application from IIS, it does not have your developer identity context to retrieve the access token. You need to configure your IIS to run with user context to retrieve the token and access the key vault. You need to follow the below steps -

  1. Configure Application pool to run as your user account.

  2. Configure setProfileEnvironment to True.
    Go to %windir%\System32\inetsrv\config\applicationHost.config Search for "setProfileEnvironment". If it's set to "False", change it to "True". If it's not present, add it as an attribute to the processModel element (/configuration/system.applicationHost/applicationPools/applicationPoolDefaults/processModel/@setProfileEnvironment), and set it to "True". Please let me know if this helps to fix your issue.

· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

SaurabhSharma-msft avatar image
0 Votes"
SaurabhSharma-msft answered ·

I have got a confirmation from Nikita on MSDN thread that the above steps helped resolved her issue.


· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.