[BUG] Unable to perform actions against site using certificate
Reporting an Issue or Missing Feature
Please confirm what it is that your reporting
When connecting to any site (root site collection or other) using Connect-PnPOnline with certificates, subsequent requests give a 401 response (tried: Get-PnPSite, Get-PnPList, Get-PnPHomePage). The same calls work if using ClientSecret instead.
Expected behavior
Same as with ClientSecret, e.g.:
| Url | CompatibilityLevel |
|---|---|
| https://company.sharepoint.com/sites/somesite | 15 |
(From Get-PnPSite -Connection $conn)
Actual behavior
Get-PnPSite : The remote server returned an error: (401) Unauthorized.
At C:\...\myscript.ps1:37 char:1
+ Get-PnPSite -Connection $conn
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [Get-PnPSite], WebException
+ FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Site.GetSite
Here is the print-out from Get-PnPException:
Message : The remote server returned an error: (401) Unauthorized.
Stacktrace : at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1
promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.SharePoint.Client.SPWebRequestExecutor.<ExecuteAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.SharePoint.Client.ClientContext.<GetFormDigestInfoPrivateAsync>d__37.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.SharePoint.Client.ClientContext.<EnsureFormDigestAsync>d__36.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.SharePoint.Client.ClientContext.<ExecuteQueryAsync>d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.SharePoint.Client.ClientContextExtensions.<ExecuteQueryImplementation>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.SharePoint.Client.ClientContextExtensions.<ExecuteQueryImplementation>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.SharePoint.Client.ClientContextExtensions.ExecuteQueryRetry(ClientRuntimeContext clientContext, Int32 retryCount,
String userAgent)
at PnP.PowerShell.Commands.PnPWebCmdlet.GetWeb()
at PnP.PowerShell.Commands.Branding.GetHomePage.ExecuteCmdlet()
at PnP.PowerShell.Commands.PnPSharePointCmdlet.ProcessRecord()
ScriptLineNumber : 40
Steps to reproduce behavior
I have tried the following steps and variations, all end up giving me the same response.
1. Register certificate using either of these methods (both work for me):
New-PnPAzureCertificate -OutPfx foo.pfx -OutCert foo.cer -CertificatePassword $pwas documented here- Using the
Create-SelfSignedCertificate.ps1script located here
2. Locally install the certificate using one of the following steps (both worked for me):
Import-Certificate -FilePath $certpath -CertStoreLocation cert:\CurrentUser\Root- Or manually install by double-clicking the certificate
- Also have tried certificates installed to both Local and CurrentUser
3. Register an Azure Application with Graph Application Permission for "Sites.ReadWrite.All"
This was done manually through the Azure Portal.
4. Grant admin access to the application and wait. I also tried following the steps described here for granting the app access to SPO. No difference.
5. Upload the generated certificate to "Certificates & secrets"
6. Connect using one of the following methods (same result for root or other site):
$conn = Connect-PnPOnline -Thumbprint $thumbprint -Tenant company.onmicrosoft.com -ClientId $clientId -Url https://company.sharepoint.com/sites/somesite -ReturnConnection$conn = Connect-PnPOnline -CertificatePath $certpath -CertificatePassword $secureCertificatePass -Tenant company.onmicrosoft.com -ClientId $clientId -Url https://company.sharepoint.com/sites/somesite -ReturnConnection
7. Attempt to get some info, e.g.:
Get-PnPSite -Connection $conn
$list = Get-PnPList -Identity "My list" -Connection $conn
$list.Title
Get-PnPHomePage -Connection $conn
I also tried the same steps without the use of the -ReturnConnection and -Connection params. Disconnect-PnPOnline was not used.
What is the version of the Cmdlet module you are running?
PnP.Powershell version: 1.3.0
PSVersion 5.1.19041.610
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.19041.610
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
Which operating system/environment are you running PnP PowerShell on?
- [x] Windows
- [ ] Linux
- [ ] MacOS
- [ ] Azure Cloud Shell
- [ ] Azure Functions
- [ ] Other : please specify
Just for my understanding, in step 3, did you point to your existing certificate when running Register-AzureADApp? If not the cmdlet will generate a new certificate, using the name given to the app. So if the app is called "Testing" then the certificates will be saved to the current folder where you run the cmdlet and it will name them "Testing.pfx" and "Testing.cer".
The extra step your tried in step 4 is not applicable to this type of connection, it only applies to 'legacy ACS' type of connections using client id and client secret.
You are not required to install the certificate in your store if you don't want to. Effectively you can skip creating the certificate manually if you want, as the Register-PnPAzureApp cmdlet can do that fully for you. If you want to store the certificate in your windows certificate store, just specify the -Store parameter with either LocalMachine or CurrentUser as a value
Register-PnPAzureADApp -Name "TestingAccess" -Tenant yourtenant.onmicrosoft.com -Scopes SPO.Sites.ReadWrite.All -Interactive
The register cmdlet has more properties if you want to specify your own common name, a password etc.
This will register the app, create a certificate and save the pfx and cer file to the file system. Just to make sure I executed the cmdlet -exactly- as I wrote above (with my own tenant name) and used the output to connect:
Connect-PnPOnline -Url https://mytenant.sharepoint.com -ClientId [id] -CertificatePath TestingAccess.pfx -Tenant mytenant.onmicrosoft.com
Get-PnPList
I received no errors and everything worked as intended.
Just to make sure, as not everyone seem to be aware of this: you do not have to return a connection if you only intend to work against a single tenant. Simply doing a Connect-PnPOnline will store the session in the current PowerShell session. Any subsequent cmdlets run after connect will use this connection automatically, so you don't have to specify -Connection $conn. The connection will be removed when you use Connect-PnPOnline again to a different site, if you close the PowerShell session or if you explicitly call Disconnect-PnPOnline. The latter is rarely needed though and only makes sense if you want to clear the in-memory token cache we're using.
Now that I read your post again, I noticed a key thing:
You provide permissions to the -Graph-. We only use the graph for a subset of the actions behind the scenes, the majority of the calls we make go directly to SharePoint. E.g. you will have to grant in your app the SharePoint Sites.ReadWrite.All right. That's also what I do when I ran the Register-PnPAzureAdApp cmdlet: I used -Scopes SPO.Sites.ReadWrite.All. (SPO as in SharePoint Online).
Heyo @erwinvanhunen, I updated my post to reflect that the application registration was done using Azure Portal rather than using Register-AzureADApp. I didn't spot the SharePoint API choice in the Portal menu any more, so I figured it had been fully replaced by Graph - found the SP Option now of course 💡
Have to request some temporary Admin access before I can test again, but I'll try consenting to the actual SharePoint site permissions as soon as I can. If that doesn't work, I'll test the cmdlet you suggested :)
Thanks so much for the quick reply 🥇
Giving the correct permissions solved the problem!