functions/public/New-GroupRoleAuthorization.ps1

function New-GroupRoleAuthorization {
    param (
        [Parameter(Mandatory = $true)] [string] $authUrl,
        [Parameter(Mandatory = $true)] $group,
        [Parameter(Mandatory = $true)] $body,
        [Parameter(Mandatory = $true)] [string] $accessToken
    )

    if (!($body -is [string])) {
        $clientObject = $body
        $body = ConvertTo-Json $body
    }
    else {
        $clientObject = ConvertFrom-Json -InputObject $body
    }

    $url = "$($authUrl.TrimEnd("/"))/groups"
    $url = "$($url)/$($group.groupName)/roles?"
    if ($group.identityProvider) {
        $url = "$($url)identityProvider=$($group.identityProvider)&"
    }
    if ($group.tenantId) {
        $url = "$($url)tenantId=$($group.tenantId)&"
    }
    $url = "$($url.TrimEnd("?").TrimEnd("&"))"

    $headers = @{"Accept" = "application/json"}
    if ($accessToken) {
        $headers.Add("Authorization", "Bearer $accessToken")
    }

    # attempt to add
    try {
        $response = Invoke-RestMethod -Method Post -Uri ([System.Uri]::EscapeUriString($url)) -Body $body -ContentType "application/json" -Headers $headers
        Write-DosMessage -Level "Information" -Message """$($clientObject.name)"" role associated with ""$($group.groupName)"" group"
        return $response
    }
    catch {
        $exception = $_.Exception
        if ($null -ne $exception -and $null -ne $exception.Response) {
            $error = Get-ErrorFromResponse -response $exception.Response
            if ($error.Contains("$($clientObject.id) already exists")) {
                Write-DosMessage -Level "Information" -Message """$($clientObject.name)"" role already associated with ""$($groupName)"" group"
            }
            else {
                throw ( New-Object -TypeName "System.Net.WebException" "There was an error associating ""$($clientObject.name)"" role to the ""$($group.groupName)"" group: $error, halting installation.", $exception)
            }
        }
        else {
            $error = "Unknown error attempting to post"
            $exception = $_.Exception
            if ($null -ne $exception -and $null -ne $exception.Response) {
                $error = Get-ErrorFromResponse -response $exception.Response
            }
            throw ( New-Object -TypeName "System.Net.WebException" "There was an error associating ""$($clientObject.name)"" role to the ""$($group.groupName)"" group: $error, halting installation.", $exception)
        }
    }
}