functions/public/New-PermissionAuthorization.ps1

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

    $url = "$($authUrl.TrimEnd("/"))/permissions"

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

    $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)"" has been added as a new permission"
        return $response
    }
    catch {
        $exception = $_.Exception
        if ((Assert-WebExceptionType -exception $exception -typeCode 409)) {
            $url = "$($url)/$($clientObject.grain)/$($clientObject.securableItem)/$($clientObject.name)"
            $response = Invoke-RestMethod -Method Get -Uri ([System.Uri]::EscapeUriString($url)) -ContentType "application/json" -Headers $headers
            return $response
        }
        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 creating permission ""$($clientObject.name)"": $error, halting installation.", $exception)
        }
    }
}