MS Graph API Grant permission to shared lnik

Viewed 17

I'm developing a Powershell script that generates Shared links from SharePoint folders and gives access to specific users.

I managed to create the link, but I'm struggle to give access to the specific user.

This is my code :

Create the link This function returns the Shared link URl and the Shared link ID

function CreateSharingLink($folderID)
{
       $Uri = "https://graph.microsoft.com/v1.0/drives/$($drivdeId)/items/$($folderID)/createLink"

       $params = @{"type"="view";
                   "scope"="users"
                  }

       $response= Invoke-MgGraphRequest -Uri $Uri -Method Post -Body $params

       write-host ($response | ConvertTo-Json)

       return $response.link.webUrl, $response.id
}

Grant permission to specific user

This function failed

function GivePermissionToSharingLink($userEmail, $sharedDriveItemId)
{
     $params = @{
                  Recipients = @(
                       @{
                            Email = $userEmail
                        }
                  )
                  Roles = @(
                         "read"
                  )
        } 

        $response = Grant-MgSharePermission -SharedDriveItemId $sharedDriveItemId -BodyParameter $params

}

The sharedDriveItemId is the ID previously returned by the created function

This is the error

Error

Finally, This is my application rights

enter image description here

Any ideas ? Thanks

1 Answers

You need to encode $sharedDriveItemId. Based on the documentation you need encoded sharing url.

function GivePermissionToSharingLink($userEmail, $sharedDriveItemId)
{
     $params = @{
                  Recipients = @(
                       @{
                            Email = $userEmail
                        }
                  )
                  Roles = @(
                         "read"
                  )
        } 

    $base64Value = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($sharedDriveItemId))
    $encodedUrl = "u!" + $base64Value.TrimEnd('=').Replace('/','_').Replace('+','-')

    $response = Grant-MgSharePermission -SharedDriveItemId $encodedUrl -BodyParameter $params

}

Resources:

Encoding sharing URLs

Related