Azure Active Directory - 如何以编程方式将应用程序角色分配给组

Azure Active Directory - how to assign application role to group programmatically

我正在寻找使用 Azure AD 创建基于角色的授权 mvc 应用程序:

从 Azure 门户,我可以:

我刚刚获得了 免费的 Azure Active Directory 版本,并且我读到我们可以使用 Microsoft Azure Active Directory 来执行这些操作:

Microsoft 提供 good samples 查询 AAD,我已经开始使用它,但我不知道如何将应用程序分配给组。

这是我获取群组的伪代码:

ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
var app = (await client.Applications.GetByObjectId("applicationObjectId").ExecuteAsync());
var servicePrincipal = await client.ServicePrincipals.GetByObjectId("servicePrincipalObjectId").ExecuteAsync();
var appRole = app.AppRoles.First(r => r.DisplayName == "my role");
var mygroup = (await client.Groups.ExecuteAsync()).CurrentPage.FirstOrDefault();           

我想做的是这样的事情:

mygroup .AppRoleAssignments.Add(new AppRoleAssignment()
{
    ResourceId = Guid.Parse(servicePrincipal.ObjectId),
    Id = appRole.Id,
    PrincipalType = "Group",
    PrincipalId = Guid.Parse(mygroup .ObjectId),
});
await group.UpdateAsync();

但是AppRoleAssignments的类型是IPagedCollection<IAppRoleAssignment>并且没有Add方法。

有人知道我需要在我的代码中更改什么吗?

其实很简单...我不得不将 IGroup 转换为 Group :

ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
var app = (await client.Applications.GetByObjectId("applicationObjectId").ExecuteAsync());
var servicePrincipal = await client.ServicePrincipals.GetByObjectId("servicePrincipalObjectId").ExecuteAsync();
var appRole = app.AppRoles.First(r => r.DisplayName == "my role");
var mygroup = (Group)(await client.Groups.ExecuteAsync()).CurrentPage.FirstOrDefault();  

而且效果很好 ^^ :

mygroup .AppRoleAssignments.Add(new AppRoleAssignment()
{
    ResourceId = Guid.Parse(servicePrincipal.ObjectId),
    Id = appRole.Id,
    PrincipalType = "Group",
    PrincipalId = Guid.Parse(mygroup .ObjectId),
});
await group.UpdateAsync();