Get-PnPTenantSite : Attempted to perform an unauthorized operation

2.5k Views Asked by At

Currently we get an access token and then pass this token to PowerShell script to loop across all ODFB personal sites.

$url = "https://XXXXX-admin.sharepoint.com"
$conn = Connect-PnPOnline -Url $url -AccessToken $access_token -ReturnConnection
$sitecollections = Get-PnPTenantSite -IncludeOneDriveSites:$true -Filter "Url -like '-my.sharepoint.com/personal/'" -Connection $conn | Select-Object -ExpandProperty Url
foreach ($site in $sitecollections)
{
    ....
}

It worked successfully for years until it was broken a while ago. I tried different versions of PnP PowerShell:

PnP version Error
SharePointPnPPowerShellOnline 3.21.2005.2 (currently used) Get-PnPTenantSite : Attempted to perform an unauthorized operation.
SharePointPnPPowerShellOnline 3.29.2101.0 Get-PnPTenantSite : The current connection holds no SharePoint context.
PnP.PowerShell 1.10.28 Get-PnPTenantSite : Attempted to perform an unauthorized operation.

If I change script to use an user/password instead the access token, the script works without problems:

$url = "https://XXXXX-admin.sharepoint.com"
$User = "[email protected]"
$PWord = ConvertTo-SecureString -String "Password" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$conn = Connect-PnPOnline -Url $url -Credentials $Credential -ReturnConnection
$sitecollections = Get-PnPTenantSite -IncludeOneDriveSites:$true -Filter "Url -like '-my.sharepoint.com/personal/'" -Connection $conn | Select-Object -ExpandProperty Url
foreach ($site in $sitecollections)
{
    ....
}

So the error happens when the script connects to SP Online using an access token. Perhaps the some things were changed. But what exactly? Have some scope to be added when an access token is requested? Or have some new permissions to be added for the application in Azure AD?

Update: Modified the script (added Write-Output "Connection is:" $conn | fl) to provide more details about connection and got the difference in ConnectionType property when SharePointPnPPowerShellOnline 3.21.2005.2 is used:

  1. When an access token is used (and the script doesn't work properly), ConnectionType : O365
  2. When an access token is used (and the script works fine), ConnectionType : TenantAdmin
0

There are 0 best solutions below