Forum Discussion
Invoke-RestMethod Upload a File to Sharepoint 401 error
- Mar 01, 2024I took a step back and started again and after a little more research I found a method that works. I moved away from Client Secret to a certificate and used PNP.Powershell. There is loads of work in getting this running but at least I have an unattended script now.
$tenant = “xxxxxxx”
$url = "https://$tenant.sharepoint.com/sites/ITandSoftware"
$file = "c:\temp\test.txt"
$ClientID = "xxxxxxxxxxxxxx"
$CertThumb = 'xxxxxxxxxxxxxxxxxx'
Connect-PnPOnline $url -ClientId $ClientID -Tenant $tenant.onmicrosoft.com -Thumbprint $CertThumb
Add-PnPFile -folder "Shared Documents/Calls" -path $file
I thought I would share in case anyone wanted to know the conclusion.
Thanks for responses though, it helps to know there is some help out there when needed.
A quick but important correction to my write-up above is that I wasn't thinking clearly and added the wrong permission (shown in the second screenshot).
I added the Sites.Read.All from the SharePoint category, which is fine when using the SharePoint URL approach, but incorrect when using the Graph approach.
I should have added the Sites.Read.All permission from within the Microsoft Graph category, given I intended to test using the Graph-based URLs.
Having added the correct application permission, I can see the relevant SharePoint content. There was no need for me to adjust any permissions within SharePoint itself.
After connecting to Microsoft Graph using the Connect-MgGraph commandlet (using certificate-based authentication), I successfully verified access using the following two commandlets:
- Get-MgBetaAllSite (Microsoft.Graph.Beta.Sites) | Microsoft Learn
- Invoke-MgGraphRequest (Microsoft.Graph.Authentication) | Microsoft Learn
You wouldn't use the second commandlet unless you were leveraging something not bundled into the "normal" commandlet (Get-MgBetaAllSite), however, I've included it for completeness.
Anyhow, as I said earlier, SharePoint isn't my thing. If you want to continue to use the SharePoint URL approach, then you can ignore all that I've included above, as I haven't tested that approach.
The main takeaway for me is that I did not have to take any action in relation to setting any permissions inside SharePoint itself. It was just setting the servicePrincipal API permissions, after which everything simply worked.
Cheers,
Lain
$tenant = “xxxxxxx”
$url = "https://$tenant.sharepoint.com/sites/ITandSoftware"
$file = "c:\temp\test.txt"
$ClientID = "xxxxxxxxxxxxxx"
$CertThumb = 'xxxxxxxxxxxxxxxxxx'
Connect-PnPOnline $url -ClientId $ClientID -Tenant $tenant.onmicrosoft.com -Thumbprint $CertThumb
Add-PnPFile -folder "Shared Documents/Calls" -path $file
I thought I would share in case anyone wanted to know the conclusion.
Thanks for responses though, it helps to know there is some help out there when needed.