Thomas
Thomas

Reputation: 29491

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 :

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 :

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 ?

Upvotes: 1

Views: 4620

Answers (1)

Thomas
Thomas

Reputation: 29491

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

Upvotes: 2

Related Questions