如何使用流利的 API 创建 Azure AD 应用程序?

How can I create an Azure AD application using the fluent API?

我正在使用以下代码尝试以编程方式在 Azure Active Directory 中注册应用程序:

        var application = azure.ActiveDirectoryApplications.Define(applicationName)
            .WithSignOnUrl(url)
            .WithIdentifierUrl(url)
            .WithAvailableToOtherTenants(false)
            .DefinePasswordCredential(id)
              .WithPasswordValue(secret)
              .Attach()
            .Create();

其中 azureMicrosoft.Azure.Management.Fluent.Azure 的实例。

当我 运行 创建 Azure Active Directory 应用程序时,抛出 Microsoft.Azure.Management.Fluent.Azure 异常并显示消息 Operation returned an invalid status code 'Forbidden'。创建其他 Azure 资源(如资源组和应用服务)工作正常。

查看异常详细信息,我可以看到向以下端点发出了请求:

https://graph.windows.net/{myTenantId}/applications?api-version=1.6

响应正文如下:

{"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"Insufficient privileges to complete the operation."}}}

由于机构说 "Insufficient privileges to complete the operation",这似乎是一个简单的权限问题,但我已授予 Microsoft.Azure.ActiveDirectory [=42] 以下权限(同时以全局管理员身份登录) =] 对于 运行 代码的应用程序:

这些特权还不够吗?我错过了什么?正如我所说,使用流畅的 API 创建其他资源效果很好。

范围 Directory.AccessAsUser.AllDirectory.ReadWrite.All User.Read 足以在 Azure Active Directory 中创建应用程序。由于您没有提供构建 azure 实例的方式,因此我将提供一个工作代码示例:

static void Main(string[] args)
{
    var url = "http://adfei.onmicrosoft.com/appFluent";
    var id = "abc";
    var secret = "secret";
    var applicationName = "appFluent";
    var credFile = new AzureCredentials(new UserLoginInformation
    {
        ClientId = "{appId of native application}",
        UserName = "{userName}",
        Password = "{password}"
    },
        "adfei.onmicrosoft.com", AzureEnvironment.AzureGlobalCloud);
    IAzure azure = Azure.Authenticate(credFile).WithDefaultSubscription();
    var application = azure.ActiveDirectoryApplications.Define(applicationName)
    .WithSignOnUrl(url)
    .WithIdentifierUrl(url)
    .WithAvailableToOtherTenants(false)
    .DefinePasswordCredential(id)
      .WithPasswordValue(secret)
      .Attach()
    .Create();

    Console.Read();
}

并且请确保范围包含在访问令牌中,以确保您拥有此操作的权限。您可以通过 Fiddler 捕获请求以检查令牌并从 this site 解码令牌以检查访问令牌中的 scp 声明。