如何在C#中使用Azure Active Directory Graph客户端创建角色分配?

时间:2016-08-29 19:32:55

标签: c# azure-active-directory

我正在使用此库:Microsoft.Azure.ActiveDirectory.GraphClient class:ActiveDirectoryClient

我想提交申请表(我有appID)"所有者"访问一些订阅。我该怎么做呢?感谢

1 个答案:

答案 0 :(得分:1)

这个问题的整个前提是不正确的。 GraphClient不是管理此类授权的正确客户端。适当的API库是Microsoft.Azure.Management.Authorization和类AuthorizationManagementClient

我将发布有关实际通话顺序的其他说明。

***更新***********

正如这里所承诺的示例代码:

    public static async Task<IServicePrincipal> GetServicePrincipalAsync(string accessToken, string tenantId, string clientId)
    {
        var graphClient = NewActiveDirectoryClient(accessToken, tenantId);
        var matches = await graphClient.ServicePrincipals.Where(sp => sp.AppId == clientId).ExecuteAsync();
        return matches.CurrentPage.ToList().FirstOrDefault();
    }
    private static ActiveDirectoryClient NewActiveDirectoryClient(string accessToken, string tenantId)
    {
        TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
        tcs.SetResult(accessToken);
        return new ActiveDirectoryClient(
            new Uri($"{GraphApiBaseUrl}{tenantId}"),
            async () => { return await tcs.Task; });
    }

首先,您需要获取要添加的主体的ObjectId。在ServicePricipal的情况下,我有一个函数可以从目录中获取它,如下所示:

然后使用它和范围(&#34; / subscriptions / {my_subscription_id}&#34;,对于整个订阅),您可以创建RoleAssignment:

    public static async Task AssignRoleToPrincipalAsync(
        string accessToken, 
        string subscriptionId, 
        string scope, 
        string roleName,
        string principalObjectId)
    {
        using (var client = NewAuthorizationManagementClient(accessToken, subscriptionId))
        {
            RoleDefinition roleDef = (await FindRoleDefinitionAsync(accessToken, subscriptionId, scope, roleName)).FirstOrDefault();
            if (roleDef == null)
                throw new Exception($"Role was not found: {roleName}");
            var props = new RoleAssignmentProperties()
            {
                PrincipalId = principalObjectId,
                RoleDefinitionId = roleDef.Id
            };
            await client.RoleAssignments.CreateAsync(scope, Guid.NewGuid().ToString("N"), props);
        }
    }

    private static AuthorizationManagementClient NewAuthorizationManagementClient(string accessToken, string subscriptionId)
    {
        return new AuthorizationManagementClient(new TokenCredentials(accessToken)) { SubscriptionId = subscriptionId};
    }