Search code examples
powershellsharepointoffice365

Granting permissions to upload a file to sharepoint using PnP Powershell - 401 Unauthorized


I am trying to grant an application registration access to upload files to a sharepoint site using PnP Online. All the commands seem to work, but when i try uploading a file i get a 401 error. I would appreciate any expertise on how to make this work. The steps ive followed are::

  1. create app registration
  2. Add sharepoint Sites.FullControl.All api permissions & approve it.
  3. Create self signed certificate, convert it to .cer & upload it.
  4. Connect using Connect-PnPOnline. this returns no errors.
  5. run Grant-PnPAzureADAppSitePermission. Again this returns no errors.
  6. run AddPnPFile. This gives the error 401 Unauthorized.

All code is below along with a screenshot of the output. Appreciate any help on this.

$Sites_FullAccess_App_ID = "19ef4773-433b-46ac-9859-865824293acd"
$Sites_FullAccess_Obj_ID = "6f8b2588-96ed-4a78-ab81-9cda9730a798"
$Sites_FullAccess_Name = "Sites_FullAccess"
$Sites_FullAccess_Secret = "~c754~9vkHcvUajPsDr.eH1X59iHEJ4d3FjybcYy"
$Tenant_Id = "601141a3-a812-4670-ac30-03f9db120f15"
$Tenant_DN = "myorg.onmicrosoft.com"
$CertThumbprint = "7CAE02F3A045258758522FF54552D356A6753159"
$securePasswordString = ConvertTo-SecureString "mY_Certif1cate-PassCDRD" -AsPlainText -Force
$CertificatePath = "C:\temp\Sites_FullAccess Certificate.pfx"
$SiteUrl = "https://myorg.sharepoint.com/sites/mysite"

Connect-PnPOnline -Url $SiteUrl `
    -ClientId $Sites_FullAccess_App_ID `
    -CertificatePath $CertificatePath `
    -CertificatePassword  $securePasswordString `
    -Tenant $Tenant_DN `
    -Verbose `
    #-ReturnConnection

Grant-PnPAzureADAppSitePermission -Site $SiteUrl `
    -AppId $Sites_FullAccess_App_ID `
    -DisplayName $Sites_FullAccess_Name `
    -Permissions FullControl 
    
Add-PnPFile -Path "C:\temp\testfile.txt" -Folder "QuercusFiles" -Connection $connection

Output from running commands


Solution

  • I eventually found the answer for this. I had to force install the latest, pre-release of PnpOnline:

    Install-Module PnP.PowerShell -AllowPrerelease -SkipPublisherCheck -Force
    

    I had only just installed the latest release version, so im assuming a recent bug was in play.

    on installing the prerelease version, it just started working.