Featured image of post Day 51: Adding Azure AD roles to on-prem AD Groups

Day 51: Adding Azure AD roles to on-prem AD Groups

A quick look at a PowerShell script to help with this.

I recently had an interesting request with regards to assigning an Azure role to a group that’s synced from Active Directory.

If you’ve ever had to-do this before, then you’ll know that natively this isn’t normally possible and for good reason (we should be assigning users directly to the roles, this ensures proper management of the role and fits in with the modern way of doing things), however there are instances where solutions are needed irrespective. You have recently been able to assign Az roles to cloud groups, which is nice but kind of useless if your using on prem groups, its also kind of useless if your using cloud groups for role purposes because someone will need to manually add users into that cloud group, unless you have some form of automation in place via a service management tool. You will also find that users who leave the company may also not be automatically removed from the group, which could be a potential issue if you don’t have some form of control for that, being disabling the account or removing 2FA etc, rendering the account useless when they leave - however as previously mentioned, a proper service management tool that’s setup correctly should cover this.

So how would we typically approach this if adding a few users? You would probably use something like below:

Add-AzureADDirectoryRoleMember

https://docs.microsoft.com/en-us/powershell/module/azuread/add-azureadgroupmember?view=azureadps-2.0

Simple enough, but what if we want to add more users to the role? Well the good news this is possible (as is anything) but we need to use a script to-do what we need. The following script was written by John Savill (https://savilltech.com/2019/10/30/small-script-to-grant-azure-ad-roles-to-groups/), and it worked great but using my limited knowledge, I decided to try and mod it a bit to fit my needs. The issue I had was the names of the groups I was referencing, had similar names within our estate, meaning when the script is going off and trying to find an objectID, it cant resolve which one to pick as there are similar ones, so it would just kick me out and error with something typically generic. Eventually when I figured out what the root cause was after a couple hours, it was easy to fix and thankfully can share this so hopefully it helps someone else.

The command that needed changing was: $groupObject = Get-AzureADGroup -SearchString “$groupName”

The -SearchString was causing the issue when trying to get the group to resolve, changing this to Get-AzureADGroup -Filter “DisplayName eq ‘$groupName’” or Get-AzureADGroup -ObjectId “$groupName” means you can be more specific with the object your targeting, meaning were now either specifying the exact name of the group or in some instances if you have a security group and distribution group with the same name, then you’ll need to specify the objectID itself.

So, onto the script. It essentially it takes 2 values, the Group Name and the Azure Role you want to add the members of the group to.

It scans the group, see’s who’s a member of a role and then adds the user if needed, and loops through until it finishes - this is probably the quickest way to perform this action without using some third party tool. Unfortunately, if the group is nested as most DL/SG are, then the script will only do the top level members, meaning any nested members will need to be done separately, my plan is to make the script note the nested members and apply the change against those also but that’s for when I have time to take a proper look. If you do need to apply to nested members, then keeping the window open and switching out the name for the $GroupName value will do and is quick enough, and if you need to query the objectID itself then you can do this via the portal itself or using the Get-ADObject function, more info at: (https://docs.microsoft.com/en-us/powershell/module/activedirectory/get-adobject?view=windowsserver2022-ps&viewFallbackFrom=windowsserver2022-psget-azobject).

You would call the function by using something like: Example Add-RoleToGroup “Teams Communications Support Engineer” “!Name of DL/SG etc.”

Thanks for reading!

Function Add-RoleToGroup

{

    [CmdletBinding()]

    param (

        [Parameter(Position=0,Mandatory=$true)]

        [String]

        $roleName,

        [Parameter(Position=1,Mandatory=$true)]

        [String]

        $groupName

    )

    #$roleName = ""

    #$groupName = ""

 

    Write-Output "Granting $RoleName to $GroupName"

 

    $errorFound = $false

 

    #Note that only roles that are enabled, i.e. have at least one person in them will be found using this command so ensure at least one person is in the desired group

    $roleObject = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq $roleName}

    if($null -eq $roleObject)

    {

        write-output "Cannot find role $roleName, it may be it is not enabled. Ensure the group already has at least one person in it"

        $errorFound = $true

    }

       # Decide which below you want to use, see blog for info.

 

       # Use this (original) to add role to members, use this is its only group that exists with the name.

              # $groupObject = Get-AzureADGroup -SearchString "$groupName"

 

       # Use this to specify the exact name if more than 1 group exists with similar name, specify exact name.

              $groupObject =  Get-AzureADGroup -Filter "DisplayName eq '$groupName'"

 

       # Use if multiple same names in AD/AZ, i.e. a DL and SG with same name, then use the ObjectId of group.

              # $groupObject =  Get-AzureADGroup -ObjectId "$groupName"

 

    if($null -eq $groupObject)

    {

        write-output "Cannot find group $groupName"

        $errorFound = $true

    }

 

    if(!$errorFound)

    {

        $groupMembers = Get-AzureADGroupMember -ObjectId $groupObject.ObjectId -All $true #| Select-Object -ExpandProperty UserPrincipalName

       $roleMembers = Get-AzureADDirectoryRoleMember -ObjectId $roleObject.ObjectId #| Select-Object -ExpandProperty UserPrincipalName

 

        $userDifferences = Compare-Object $groupMembers $roleMembers

 

        foreach($UserDifference in $UserDifferences)

        {

            # if need to add

            if($UserDifference.SideIndicator -eq "<=")

            {

                Write-Output "Adding $($UserDifference.InputObject.userprincipalname) to role"

                try

                    {Add-AzureADDirectoryRoleMember -ObjectId $roleObject.ObjectId -RefObjectId $UserDifference.InputObject.ObjectId}

                catch { "Error adding role"}

            }

        }

    }

}