skip to Main Content

Im trying to add the global reader role to an app registration, but somehow my code below is not working and the result count is always 0.

var directoryRoles = await graphServiceClient.DirectoryRoleTemplates.GetAsync();
var result = await graphServiceClient.DirectoryRoles.GetAsync((requestConfiguration) =>
{
    requestConfiguration.QueryParameters.Filter = $"roleTemplateId eq '{tmplRole!.Id}'";
});
var Role = result.Value!.FirstOrDefault();

The result.count is 0 and I don’t understand why it would be? The global reader clearly exists and the tmplRole.Id contains an Id.

What also frustrates me is that var directoryRoles = await graphServiceClient.DirectoryRoles.GetAsync(); will only show activated roles?

2

Answers


  1. Chosen as BEST ANSWER

    As user2250152 stated, you need to "create" the role first before you can get the directory role.

    This fixed it for me:

                DirectoryRole globalReaderRole;
    
                if (result.Value.Count == 0)
                {
                    globalReaderRole = await graphServiceClient.DirectoryRoles.PostAsync(new DirectoryRole
                    {
                        RoleTemplateId = tmplRole.Id 
    
                    });
                }
                else
                {
                    globalReaderRole = result.Value.FirstOrDefault();
                }
    

  2. Yes, /directoryRoles returns only activated roles as mentioned in the doc.

    Microsoft recommends to use RBAC API. If you know the templateRoleId, you can use the RBAC API and assign the role to the application.

    var requestBody = new UnifiedRoleAssignment
    {
        OdataType = "#microsoft.graph.unifiedRoleAssignment",
        RoleDefinitionId = $"{tmplRole!.Id}",
        PrincipalId = $"{servicePrincipalId}",
        DirectoryScopeId = "/",
    };
    
    var result = await graphServiceClient.RoleManagement.Directory.RoleAssignments.PostAsync(requestBody);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search