Connect-PnPOnline with an app registration and app-only token – Engineerer
419
post-template-default,single,single-post,postid-419,single-format-standard,wp-custom-logo,bridge-core-3.1.2,qode-page-transition-enabled,ajax_fade,page_not_loaded,,footer_responsive_adv,hide_top_bar_on_mobile_header,qode-content-sidebar-responsive,qode-theme-ver-30.1,qode-theme-bridge,qode_header_in_grid,elementor-default,elementor-template-full-width,elementor-kit-641,elementor-page-1064
locked gate

Connect-PnPOnline with an app registration and app-only token

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 🎉