Connect to Sharepoint Online using Powershell and Entra Service Principal

Our goal is to connect to SharePoint Online using a service principal in Entra ID utilizing PowerShell. You can use this approach to connect to SharePoint Online when creating an unattended PowerShell script.

The steps outlined in this blog post will guide you in creating a connection to SharePoint Online without any username/password prompts. Instead, we will utilize a self-signed certificate, ClientID, tenantID, and SiteURL for the SharePoint Online connection.

A self-signed certificate PFX file is created to establish a connection to SharePoint Online. While you can store this certificate on your local device for connection purposes, it is important to note that this method is not entirely secure. This is because possessing the certificate and its private key grants anyone access to the app and the permissions it has been granted, allowing them to connect to SharePoint Online.

An alternative approach involves storing the certificate in Azure Key Vault, retrieving it using PowerShell commands, and subsequently utilizing the certificate in the Connect-PnPOnline command to establish a SharePoint connection. For detailed instructions, refer to this step-by-step guide on connecting to SharePoint Online using Azure Key Vault and Connect-PnPOnline.

We will grant read-only rights to this service principal for all SharePoint sites. If you require read and write access to the SharePoint sites, you must update the API Permissions in the App Registration for this service principal.

Steps to Connect to Sharepoint Online Using Entra Service Principal

  1. Create a Self-Signed certificate.
  2. Create a Service principal/App Registration in Entra ID.
  3. Connect the Certificate to the Application.
  4. Use the Connect-PnPOnline command to connect to Sharepoint Online.

Step 1 – Create a Self-Signed Certificate

The first step is to generate a new 2048-bit self-signed certificate. It’s important to note that anyone possessing the certificate and its private key can use the app and the permissions granted to it to connect to SharePoint Online. To create a self-signed certificate, we will use the New-PnPAzureCertificate PowerShell cmdlet.

  1. Use the following PowerShell code to create a self-signed certificate. Replace the variables in the code according to your requirements and execute the code to generate a certificate.

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
  • The screenshot below displays the output of the above commands. Once you execute these commands, a certificate named AzureSPOConnection.pfx will be created at the location specified in the outpfx parameter.
Step 1 - Create a Self-Signed Certificate
Step 1 – Create a Self-Signed Certificate
  1. Run the command $cert.KeyCredentials | clip.exe and copy the value to a notepad or another location. We will need this value later during the App registration configuration in Entra ID.
Step 1 - Create a Self-Signed Certificate
Step 1 – Create a Self-Signed Certificate

Step 2 – Create a Service Principal in Entra ID

The next step is to create a service principal in Entra ID. Follow the steps below:

  1. Log in to the Entra Admin Center.
  2. Navigate to Applications > click on App registrations.
  3. Click on + New registration.
  4. On the Register an Application page, provide a relevant Name, for example: SPOServicePrincipal.
  5. Select the supported account type: Accounts in this organization directory only (<your org> only – Single tenant).
  6. Click on Register to create an App registration.
Step 2 - Create a Service Principal in Entra ID
Step 2 – Create a Service Principal in Entra ID

2.1 Add API Permissions to the Service Principal

Add API Permissions to this service principal. According to our requirements, we need to grant read-only access to all SharePoint sites for this service principal. Follow the steps below to add API Permissions:

  1. Navigate to the newly created service principal.
  2. Click on API permissions under Manage.
  3. Click on + Add a permission under Configured permissions.
2.1 Add API Permissions to the Service Principal
2.1 Add API Permissions to the Service Principal
  1. From the Request API permissions pane, under Microsoft APIs, scroll down to find SharePoint API and click on it.
2.1 Add API Permissions to the Service Principal
2.1 Add API Permissions to the Service Principal
  1. Select “Application permissions“, and then choose “Sites.Read.All” permission to grant read-only access to this service principal for all SharePoint Online site collections.
  2. Click on “Add permissions” to add the permission.
2.1 Add API Permissions to the Service Principal
2.1 Add API Permissions to the Service Principal
  1. Click on “Grant admin consent for <yourorg>“. If prompted, click the “Yes” button. Ensure that the status displays a green tick to confirm that admin consent has been granted.
2.1 Add API Permissions to the Service Principal
2.1 Add API Permissions to the Service Principal

Step 3 – Connect the Certificate to the Application

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

  1. Navigate to the service principal.
  2. Click on Manifest under Manage.
  3. Paste the $cert.KeyCredentials output in the KeyCredentials [ ] section between square brackets.
Step 3 - Connect the Certificate to the Application
Step 3 – Connect the Certificate to the Application

Step 4 – Use Connect-PnPOnline to Connect to Sharepoint Online

Now, with our certificate and service principal ready, we can proceed to create a connection to SharePoint Online using the Connect-PnPOnline PowerShell cmdlet.

The Connect-PnPOnline cmdlet is included in the PnP.Powershell module. If you have not installed this module on your device, you will not be able to run the Connect-PnPOnline cmdlet and will encounter the following 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.

  1. Install PnP.Powershell Module
    • Make sure this module is installed on your device. To Install it use the following command:
Install-Module -Name "PnP.PowerShell

Use the following PowerShell commands to connect to SharePoint Online. Replace the variables below with your Azure environment details and then execute the commands.

  • $ClientId = Copy the Client ID from the App registration.
Step 4 - Use Connect-PnPOnline to Connect to Sharepoint Online
Step 4 – Use Connect-PnPOnline to Connect to Sharepoint Online
  • $CertPath: Provide the location of the certificate PFX file generated earlier.
  • $CertPwd: Provide the password for the certificate PFX file.
  • $tenantname: Provide the tenant name. You can find the tenant name either using the Entra admin center or from the Microsoft 365 admin center.
  • $SiteUrl: Provide a SharePoint site URL to connect.

After updating the variables, copy and paste the commands into the PowerShell window to test the connection. If the connection is successful, no errors will be generated. Verify the connectivity by running the Get-PnPSite command.

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 verifying the connectivity, you can use the code in your unattended PowerShell scripts to connect to SharePoint Online and perform various tasks. As an example, you can:

  • Get the list of all SharePoint sites.
  • Retrieve all the files in a particular SharePoint site.
  • Check if SharePoint Document library files follow the company naming convention.
  • 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
Step 4 – Use Connect-PnPOnline to Connect to Sharepoint Online

Conclusion

In this blog post, we have explored how to connect to SharePoint Online using the Connect-PnPOnline command with a service principal in Entra ID and a certificate. We have granted Read-Only permissions for all SharePoint site collections to the service principal. However, it’s important to note that you can also update the permissions to Read/Write as needed.

Leave a Comment

Discover more from TechPress

Subscribe now to keep reading and get access to the full archive.

Continue reading