【问题标题】:Error when using AD to work with Azure Management API使用 AD 处理 Azure 管理 API 时出错
【发布时间】:2017-09-30 20:26:54
【问题描述】:

我正在使用 Microsoft.WindowsAzure.Management 和 Microsoft.IdentityModel.Clients.ActiveDirectory 包尝试通过 C# 代码使用 Azure 管理 API,但是当我尝试从中检索一些数据时,我总是收到错误消息:

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

这是我正在使用的代码示例:

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);

【问题讨论】:

    标签: c# azure azure-active-directory azure-management-api


    【解决方案1】:

    我相信您收到此错误是因为 Service Principal(或换句话说,Azure AD 应用程序)没有您的 Azure 订阅的权限。您需要为此服务主体分配一个角色。

    请参阅此链接,了解如何将 Azure 订阅中的角色分配给服务主体:https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal#assign-application-to-role

    一旦你这样做了,错误就会消失。

    【讨论】:

    • 我不确定您的意思,但我在订阅级别将我的应用程序作为所有者添加到 IAM,但我仍然收到此错误。顺便说一句,我可以只知道用于登录门户的用户名和密码来使用 Azure 管理 API 吗?无需为此创建单独的应用程序
    • 看起来您正在尝试使用上面的代码使用Service Management API 访问Classic Resources。请查看此线程以获取更多详细信息:stackoverflow.com/questions/35190866/…
    【解决方案2】:

    我也可以重现这个问题。要列出订阅,我们需要使用SubscriptionClient 而不是ManagementClient。这是适合我的代码:

    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);
    }
    

    注意:要使代码正常工作,我们需要使用订阅的所有者而不是证书来获取令牌。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-31
      • 2017-11-12
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 2020-11-08
      相关资源
      最近更新 更多