Connect to Sharepoint Online using Powershell

Our goal is to connect to sharepoint online using an Azure AD service principal from within Powershell. You can use this approach to connect to sharepoint online when you are creating an unattended powershell script.

Steps given in this blog post will enable you to create a connection to sharepoint online without any username / password prompts to connect. Instead we will use a self signed certificate, ClientID, tenantID and SiteURL to connect to sharepoint online.

A self signed certificate pfx file is used to create sharepoint online connection. You can store this certificate on your local device and use it to create a connection. However, its not secure as it enables anyone having the certificate and its private key to use the app and the permissions granted to the app to connect to sharepoint online. 

You can also store this certificate in Azure Keyvault, retrieve it using powershell commands and then use the certificate in Connect-PnPOnline command to create a sharepoint connection. You can use this step by step guide to Connect To Sharepoint Online Using Azure KeyVault And Connect-PnPOnline

We will provide read only rights to this service principal for all sharepoint sites. If you require read and write access to the sharepoint sites, you will need to update the API Permissions in App registration for this service principal.

Steps to connect to Sharepoint Online using Azure AD service Principal using Powershell

  1. Create a Self Signed certificate.
  2. Create an Azure AD service principal / App registration.
  3. Connect the certificate to the Application.
  4. Use Connect-PnPOnline command to connect to Sharepoint Online.

1. Create a Self Signed certificate

First step is to create generare a new 2048bit self-signed certificate. Anyone having the certificate and its private key can use the app and the permissions granted to the app to connect to sharepoint online. To create a self signed certificate, we will use New-PnPAzureCertificate powershell cmdlet.

Powershell Code to create Self Signed Certificate

$Password = "P@ssw0rd"
$SecPassword = ConvertTo-SecureString -String $Password -AsPlainText -Force

$Props = @{
    Outpfx              = "AzureSPOConnection.pfx" 
    ValidYears          = 15
    CertificatePassword = $SecPassword 
    CommonName          = "AzureSPOconnection" 
    Country             = "GB" 
    State               = "England" 
    Locality            = "London"
}

$Cert = New-PnPAzureCertificate @Props

Below screenshot shows the output of the above commands. After you execute these commands, A certificate AzureSPOConnection.pfx will be created as per the location specified in outpfx parameter.

Create a Self Signed certificate Sharepoint Online Powershell

Run the command $cert.KeyCredentials | clip.exe and copy the value in a notepad somewhere. We will need this value later during App registration configuration in Azure AD.

KeyCredentials for self signed certificate

2. Create an Azure AD service principal

Next step is to create an Azure AD service principal in Azure active directory. Follow below steps to create Azure AD service principal / App registration.

  1. Login on Azure Portal (https://portal.azure.com).
  2. Search for Azure Active Directory.
  3. Click on App registrations under manage from left hand side.
  4. Click on + New registration.
  5. On Register an Application page. Provide any relevant Name for example: SPOServicePrincipal.
  6. Select Supported account type: Accounts in this organization directory only (<your org> only – Single tenant)
  7. Click on Register to create an App registration.
Create an Azure AD service principal for Sharepoint Online Powershell

2.1 Add API Permissions to the Azure AD service principal

Add API Permissions to this service principal. As per our requirement, we need to provide read only access to all sharepoint sites to this service principal. To add API Permissions, follow below steps:

  1. Go to the newly created service principal.
  2. Click on API permissions under Manage.
  3. Click on + Add a permission under Configured permissions.
Add API Permissions to the Azure AD service principal for Sharepoint Online
  1. From Request API permissions pane, Under Microsoft APIs, scroll down to find Sharepoint API and click on it.
Request API Permissions for Sharepoint Online in Azure Active Directory
  1. Select Application permissions and then select Sites.Read.All permission to provide read only permission to this service principal for all sharepoint online site collections. Click on Add permissions to add the permission.
Provide Sites.Read.All permission to Sharepoint Azure AD service Principal
  1. Click on Grant admin consent for <yourorg>. If prompted, click on Yes button. Make sure that the status shows a green tick to confirm that admin consent has been granted.

3. Connect the certificate to the Application

Next step is to configure the App registration and add KeyCredentials value we copied in step 1. To configure KeyCredentials in the App, please follow below steps:

  • Go to the service principal.
  • Click on Manifest under Manage.
  • Paste $cert.KeyCredentials output in the KeyCredentials [ ] section between square brackets.
Add Certificate Keycredentials to the service principal for sharepoint online powershell connection

4. Use Connect-PnPOnline to connect to Sharepoint Online

We now have our certificate and service principal ready to be used for creating a connection to sharepoint online. We will be using Connect-PnPOnline powershell cmdlet.

Connect-PnPOnline cmdlet is included in PnP.Powershell module. If you have not installed this module on your device, you would not be able to run Connect-PnPOnline cmdlet and will get below error:

The term ‘Connect-PnPOnline’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Open powershell console as administrator and run the command Install-Module -Name "PnP.PowerShell" to Install PnP.Powershell module.

Use below powershell commands to connect to sharepoint online. You need to replace below variables as per your Azure environment and then execute the commands:

  • $ClientId = Copy Client ID from App registration. Click on Overview and then copy Application (client) ID.
How to find Client ID of an Application in Azure.
  • $CertPath – Provide the location of certificate pfx file generated earlier.
  • $CertPwd – Provide the password of certificate pfx file.
  • $tenantname – Provide the tenant name. You can find tenant name either using Azure Active directory or from Microsoft 365 admin center.
  • $SiteUrl – Provide a sharepoint site url to connect.

Connect to Sharepoint Online using Connect-PnPOnline

$ClientId     = "20362b41-fe1b-4255-953a-ff86ec250eb6"
$CertPath     = "C:\Temp\certstore\AzureSPOConnection.pfx"
$CertPwd      = "P@ssw0rd"
$Pwd          = (ConvertTo-SecureString -AsPlainText $CertPwd -Force)
$tenantname   = "mylab000.onmicrosoft.com"
$SiteUrl      = "https://mylab000.sharepoint.com/sites/Finance"

$Props = @{
    ClientId            = $ClientID
    CertificatePath     = $CertPath
    CertificatePassword = $Pwd
    Url                 = $SiteUrl
    Tenant              = $tenantname
}

Connect-PnPOnline @Props

After updating the variables, you can copy and paste the commands in Powershell window to test the connection. If the connection is successful, there will be no errors generated. You can verify the connectivity by running get-pnpsite command.

Once you verify the connectivity, you can use the code in your unattended powershell scripts to connect to Sharepoint online and perform various tasks. As an example:

  • Get the list of all sharepoint sites.
  • Get all the files in a particular sharepoint site.
  • Check if sharepoint Document library files are following company naming convention or not.
  • If you have provided Read / Write permission to the service principal, you can add or remove a file from the sharepoint site or delete a sharepoint site etc.
Use Connect-PnPOnline to connect to Sharepoint Online

Conclusion

In this blog post, we have seen how to connect to sharepoint online using Connect-PnPOnline command using an Azure AD service principal and a certificate. We have provided Read Only permissions for all sharepoint site collections to the service principal. But you can also update the permissions to Read / Write permissions as well.