I admit it, it’s an old topic, but today I still struggled with an app-only connection to SharePoint Online. The sole thing that helped me was jogging in the woods. You expected a reboot I know, but this is the cloud!
Microsoft explains here how to authenticate via PowerShell to SharePoint Online. It’s important to note that an app-only authentication only works by authenticating via a certificate.
WHY?
Through PnP.PowerShell SharePoint Online automation is at your fingertips: Checking OneDrives for the correct time zone, creating multiple SPO sites, cleaning up additional site collection admins.
You can connect with username, password, and a second factor, but not if the script should run unattended in the context of an Azure Automation Runbook or as an old-school scheduled task.
HOW?
- Create a certificate with private and public key.
$password = ""
$commonName = ""
$certFileNameWithoutExtension = "mycert"
New-PnPAzureCertificate -CommonName $commonName -OutPfx "$certFileNameWithoutExtension.pfx" -OutCert "$certFileNameWithoutExtension.cer" -CertificatePassword (ConvertTo-SecureString -String $password -AsPlainText -Force)
- Install the certificate by double clicking the pfx file or use parameter “-CertificatePath” with Connect-PnPOnline later.
- If you install the certificate under “Local Machine”, you need to run the PowerShell console with admin rights.
- Create an app registration by navigating to https://portal.azure.com – AAD – App registrations – “New registration”.
- Take note of the client ID and directory ID.
- Upload the generated cer-file under AAD – App Registrations – you registration – “Certificates & secrets”
- Configure required permissions under AAD – App Registrations – you registration – “API permissions”.
- Click “Add a permission” and select the required permissions under SharePoint – Application permissions
- Give admin consent by clicking “Grant admin constent for [tenant name]”
- Wait a couple of minutes
- Connect
$clientId = "GET IT FROM APP REGISTRATION PAGE"
$thumbprint = "RETURNED WHEN RUNNING New-PnPAzureCertificate"
$tenantId = "GET IT FROM APP REGISTRATION PAGE"
$connectionsParams = @{
ClientId = $clientId
Thumbprint = $thumbprint
Tenant = $tenantId
}
$spoUrl = "https://tenant.sharepoint.com"
Connect-PnPOnline -Url $spoUrl @connectionsParams
- Do your magic 🎉