GitHub Icon Image
GitHub

Audit Service Principal Access to SharePoint Sites with Sites.Selected Permissions

Summary

Ensuring the security and compliance of your SharePoint environment is crucial, especially when dealing with service principals. These entities often have elevated permissions that, if mismanaged, can lead to unauthorized access and potential data breaches. Regularly auditing these permissions is a best practice for maintaining a secure and compliant SharePoint environment.

The Sites.Selected API permission needs to be granted to the service principal.

Api Permissions Before

The Service Principal is granted access to the SharePoint site(s) using the cmdlet:

grant-PnPAzureADAppSitePermission -AppId 27f0f80f-4c32-4e49-a3ce-377fff559532 -DisplayName  p-m365  -Permissions FullControl

The script will scan any permissions granted to service principals across the tenant.

  • PnP PowerShell
param (
    [Parameter(Mandatory = $true)]
    [string] $domain
)

$adminSiteURL = "https://$domain-Admin.SharePoint.com"
$TenantURL = "https://$domain.sharepoint.com"
$dateTime = "_{0:MM_dd_yy}_{0:HH_mm_ss}" -f (Get-Date)
$invocation = (Get-Variable MyInvocation).Value

$directorypath = Split-Path $invocation.MyCommand.Path
$fileName = "entraid_site_permissions" + $dateTime + ".csv"
$outputPath = $directorypath + "\"+ $fileName

if (-not (Test-Path $outputPath)) {
    New-Item -ItemType File -Path $outputPath
}
     Connect-PnPOnline -Url $adminSiteURL -Interactive -WarningAction SilentlyContinue
        Write-Host "Getting entra id permissions..." -ForegroundColor Yellow
        $report = Get-PnPTenantSite -Filter "Url -like '$TenantURL'"| Where-Object { $_.Template -ne 'RedirectSite#0' }  | foreach-object {
        $siteUrl = $_.Url
        connect-PnPOnline -Url $siteUrl -interactive -WarningAction SilentlyContinue
        Get-PnPAzureADAppSitePermission | ForEach-Object {
        [PSCustomObject]@{
            ##add the properties from the $sharingsetting object
            Id = $_.Id
            Url = $siteUrl
            Roles = $_.Roles -join ","
            Apps = $_.Apps -join ","
        }
    }
}

$report |select *  |Export-Csv $outputPath -NoTypeInformation -Append

Check out the PnP PowerShell to learn more at: https://aka.ms/pnp/powershell

The way you login into PnP PowerShell has changed please read PnP Management Shell EntraID app is deleted : what should I do ?

Source Credit

The script first appeared "Audit Service Principal Access to SharePoint Sites with Sites.Selected Permissions".

Contributors

Author(s)
Reshmee Auckloo

Disclaimer

THESE SAMPLES ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

Back to top Script Samples
Generated by DocFX with Material UI