title: Authenticate to multiple Azure services using Service Principle (.net Core)
body: <p>I need to get access to <strong>Key Vault</strong> and <strong>Service Bus</strong> from code, using a <em>Service Principle</em> for authentication.</p>
  
  <p>I can use the following code to access Service Bus, which works as expected - when I enable to <em>Service Principle</em> in the <em>Access Policies</em> I can pull the list of topics:</p>
  
  <pre><code>var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(APPID, APPSECRET, TENANTID, AzureEnvironment.AzureGlobalCloud);
  
  var serviceBusManager = ServiceBusManager.Authenticate(credentials, SUBSCRIPTIONID);
  var serviceBusNamespace = serviceBusManager.Namespaces.List().SingleOrDefault(n =&gt; n.Name == "SERVICEBUSNAMESPACE");
  var topics = serviceBusNamespace.Topics.ListAsync().GetAwaiter().GetResult();
  </code></pre>
  
  <p>However, I also need to get some information from Key Vault and I was trying to establish a common way to authenticate.  </p>
  
  <p><strong>METHOD 1</strong></p>
  
  <p>Similar to the above, I tried this code to access KeyVault:</p>
  
  <pre><code>var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(APPID, APPSECRET, TENANTID, AzureEnvironment.AzureGlobalCloud);
  
  var kvManager = new KeyVaultClient(credentials);
  var secret = kvManager.GetSecretAsync("https://VAULTNAMESPACE.vault.azure.net", "SECRETNAME").GetAwaiter().GetResult().Value;
  </code></pre>
  
  <p>I get the the following error:</p>
  
  <blockquote>
    <p>Microsoft.Azure.KeyVault.Models.KeyVaultErrorException: 'Operation
    returned an invalid status code 'Unauthorized''</p>
  </blockquote>
  
  <p><strong>METHOD 2</strong></p>
  
  <p>This code does work for Key Vault however (showing I have correct permissions):</p>
  
  <pre><code>string GetSecret()
  {
       var client = new KeyVaultClient(GetAccessToken);
       var secret = client.GetSecretAsync("https://VAULTNAMESPACE.vault.azure.net", "SECRETNAME").GetAwaiter().GetResult();
       return secret;
  }
  
  private static async Task&lt;string&gt; GetAccessToken(string authority, string resource, string scope)
  {
       var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
       var credential = new ClientCredential(appId, appSecret);
       var tokenResult = await context.AcquireTokenAsync("https://vault.azure.net", credential);
       return tokenResult.AccessToken;
  }
  </code></pre>
  
  <p>But, again, it's a very KeyVault specific way to Authenticate and I was hoping to establish a common mechanism using <em>SdkContext.AzureCredentialsFactory</em>.  Any reason why I'd be getting an <em>Unauthorized</em> exception with the code above connecting to Key Vault?  (all is set up correctly in Azure).</p>
  
  <p>Thanks for any tips!</p>