How to restrict the SharePoint API permission to a specific site. I can see there is a a permission called Sites.Selected but there is no option to select the site. Do I need to select it at the code level or can we select it from the portal?
How to ristrict SharePoint API permission to a specific site
2.1k Views Asked by Sakaldeep Yadav At
2
There are 2 best solutions below
5
On
I tried to reproduce the same in my environment and got the results successfully like below:
I created an Azure AD Application and granted API permissions:

To restrict the SharePoint API permission to a specific site, I used the below PowerShell script:
$siteUrl = “https://xxx.sharepoint.com/sites/testruk”
$clientId = “AppClientID”
$certThumbprint = “Thumbprint”
$tenant = “xxx.onmicrosoft.com”
Connect-PnPOnline -Url $siteUrl -Interactive
$writeperm = Grant-PnPAzureADAppSitePermission -Permissions “Write” -Site $siteUrl -AppId $clientId -DisplayName “PowerShell-SharepointOnline”
$PermissionId = Get-PnPAzureADAppSitePermission -AppIdentity $clientId
Set-PnPAzureADAppSitePermission -Site $siteurl -PermissionId $(($PermissionId).Id) -Permissions “FullControl”

Now, I tried to connect to the SharePoint site and I am able to access it successfully like below:
Connect-PnPOnline -Url $siteUrl -ClientId $clientId -Thumbprint $certThumbprint -Tenant $tenant
Get-PnPList

When I tried to access another SharePoint site, I got the error like below:
Connect-PnPOnline -Url $siteUrl -ClientId $clientId -Thumbprint $certThumbprint -Tenant $tenant
Get-PnPList

You can also make use of Graph API query like below:
POST https://graph.microsoft.com/v1.0/sites/{siteId}/permissions
Content-Type: application/json
{
"roles": ["write"],
"grantedToIdentities": [{
"application": {
"id": "APPID",
"displayName": "APPName"
}
}]
}
Reference:
Controlling app access on a specific SharePoint site - Microsoft Graph
Quite a new feature, the only way to actually "select" the sites for which the permissions apply is through a Microsoft Graph Rest API call.
You'll find a nice article here Devblog Microsoft and the official document Microsoft Graph Permissions.
I haven't use this API yet though, so I can't give you more detailled instructions.