0

I'm using Microsoft.WindowsAzure.Management and Microsoft.IdentityModel.Clients.ActiveDirectory packages trying to work with Azure Management API from C# code, but when I try to retrieve some data from it, I'm always getting the error:

ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.

There's the code sample I'm using:

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.WindowsAzure.Management;

var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/mytenant");
var cc = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential("azure-app-id", "azure-app-secret");
var token = await authContext.AcquireTokenAsync("https://management.core.windows.net/", cc);

var tokenCred = new Microsoft.Azure.TokenCloudCredentials(token.AccessToken);
var client = new ManagementClient(tokenCred);
// this is where I get the error:
var subscriptions = await client.Subscriptions.GetAsync(CancellationToken.None);
Fei Xue
  • 14,369
  • 1
  • 19
  • 27

2 Answers2

1

I believe you're getting this error is because the Service Principal (or in other words the Azure AD application) does not have permission on your Azure Subscription. You would need to assign a role to this Service Principal.

Please see this link regarding how you can assign a role in an Azure Subscription to a Service Principal: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal#assign-application-to-role.

Once you do that, the error should go away.

Gaurav Mantri
  • 128,066
  • 12
  • 206
  • 241
  • I'm not sure what you meant, but I added my application as Owner to IAM on a Subscription level and I'm still getting this error. BTW, can I use the Azure Management API only knowing the username & password used to log into the portal? Without needing to create a separate app for this – Konstantin Vasilev May 03 '17 at 07:12
  • Looks like you're trying to access `Classic Resources` using `Service Management API` using the code above. Please check this thread for more details: http://stackoverflow.com/questions/35190866/error-making-azure-management-library-api-call-when-authenticating-with-azure-ac – Gaurav Mantri May 03 '17 at 07:20
0

I can reproduce this issue too. And to list the subscription, we need to use the SubscriptionClient instead of ManagementClient. Here is the code which works well for me:

var token = "";
var tokenCred = new Microsoft.Azure.TokenCloudCredentials(token);

var subscriptionClient = new SubscriptionClient(tokenCred);
foreach (var subscription in subscriptionClient.Subscriptions.List())
{
    Console.WriteLine(subscription.SubscriptionName);
}

Note:To make the code work, we need to acquire token using the owner of the subscription instead of the certificate.

Fei Xue
  • 14,369
  • 1
  • 19
  • 27