简体   繁体   中英

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

I am looking to create a role based authorization mvc application using Azure AD:

From the Azure Portal, I am able :

  • To create user and groups.
  • To assign user to group.
  • To create applications roles.
  • To create application roles (by modifying the manifest)
  • To assign an application role to a user.

I've just had a free Azure Active Directory edition and I've readed that we can use the Microsoft Azure Active Directory to perform these actions :

  • To assign multiple application roles to users.
  • To assign multiple application roles to groups.

Microsoft provides good samples to query the AAD and I've started with it but I can't figured out how to assign an application to a group.

Here is my pseudo code to get the 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 = (await client.Groups.ExecuteAsync()).CurrentPage.FirstOrDefault();           

What I would like to do is something like that :

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

But the type of the AppRoleAssignments is IPagedCollection<IAppRoleAssignment> and there is no Add method.

Does anyone knows what I need to chage in my code ?

In fact it was simple... I had to cast the IGroup as a 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();  

And it works fine ^^ :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM