locked
I have created a web application in c#.net to access the key vault from azure ,it is working when 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.. RRS feed

  • Question

  • I have created the Web application to access the key vault from azure, it working fine if we run using IIS Express, but not working if we host on IIS.

    I want know the solution here .. since app will be hosted on IIS only OR it is only due to some permission issue...


    Please help me out as soon as possible.....
    Wednesday, April 1, 2020 11:05 AM

Answers

  • Hi,

    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.

    • Marked as answer by Nikita Pandey Friday, April 3, 2020 7:33 AM
    Friday, April 3, 2020 12:48 AM

All replies

  • Can you please provide details here ? How are you trying to access the key vault ? Are you using managed identities? What is the error message you are getting ? 
    Wednesday, April 1, 2020 9:23 PM
  • Yes I am using an App Service with managed identities.

    Following is the 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 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:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\azure-cli-core\azure\cli\core\_session.py", line 48, in load
      File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\codecs.py", line 897, in open
        file = builtins.open(filename, mode, buffering)
    PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\system32\\config\\systemprofile\\.azure\\azureProfile.json'
    During handling of the above exception, another exception occurred:
    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 562, in get_default_cli
      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\azure-cli-core\azure\cli\core\__init__.py", line 53, in __init__
      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\azure-cli-core\azure\cli\core\_session.py", line 61, in load
      File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-9101vebg\azure-cli-core\azure\cli\core\_session.py", line 65, in save
      File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\codecs.py", line 897, in open
        file = builtins.open(filename, mode, buffering)
    PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\system32\\config\\systemprofile\\.azure\\azureProfile.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 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.

    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 help me out as soon possible....

    Thursday, April 2, 2020 6:04 AM
  • Hi,

    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.

    • Marked as answer by Nikita Pandey Friday, April 3, 2020 7:33 AM
    Friday, April 3, 2020 12:48 AM
  • Hi,

    It is working fine when hosting the application in IIS, as I have follow the above steps.

    Thank you......

    Friday, April 3, 2020 7:33 AM
  • Nice..Great to hear that it worked for you :)
    Friday, April 3, 2020 6:27 PM