Dustin Laine
Dustin Laine

Reputation: 38503

Azure AD Add AppRoleAssignment

I am using Azure AD for the authentication service on an MVC application. I am managing the user accounts successfully using the Graph API. I am trying to add an AppRoleAssignment to the user.

string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

Uri servicePointUri = new Uri(graphResourceID);
Uri serviceRoot = new Uri(servicePointUri, tenantID);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetTokenForApplication());

IUser user = new User();
user.JobTitle = "Tester";
user.DisplayName = "Test Tester";
user.Surname = "Tester";
user.GivenName = "Test";
user.UserPrincipalName = "[email protected]";
user.AccountEnabled = true;
user.MailNickname = "ttester";
user.PasswordProfile = new PasswordProfile
{
    Password = "XXXXX",
    ForceChangePasswordNextLogin = true
};
await activeDirectoryClient.Users.AddUserAsync(user);

var appRoleAssignment = new AppRoleAssignment
{
    Id = Guid.Parse("XXXXX"),
    ResourceId = Guid.Parse("XXXXX"),
    PrincipalType = "User",
    PrincipalId = Guid.Parse(user.ObjectId)
};

user.AppRoleAssignments.Add(appRoleAssignment);
await user.UpdateAsync();

The AppRoleAssignment is never made. I am not certain if it is the constructor variables.

The id I am placing the ID of the role, being created in the application manifest. The ResourceId I am placing the ObjectId of the application. The application is created under the AAD Directory.

The code actually completes without error, however inspecting the user it shows not AppRoleAssignments.

In the end I am trying to implement RBAC using application roles.

Any help is greatly appreciated.

Upvotes: 2

Views: 717

Answers (1)

Thomas
Thomas

Reputation: 29481

To assign application role to a user, you need to cast the User object to IUserFetcher:

await ((IUserFetcher)user)
    .AppRoleAssignments.AddAppRoleAssignmentAsync(appRoleAssignment);

I also had to set the ResourceId to the ServicePrincipal.ObjectId

var servicePrincipal = (await
            activeDirectoryClient.ServicePrincipals.Where(
                s => s.DisplayName == "MyApplicationName").ExecuteAsync()).CurrentPage
            .First();

var appRoleAssignment = new AppRoleAssignment
{
    Id = Guid.Parse("XXXXX"),
    // Service principal id go here
    ResourceId = Guid.Parse(servicePrincipal.ObjectId),
    PrincipalType = "User",
    PrincipalId = Guid.Parse(user.ObjectId)
};

Upvotes: 4

Related Questions