Tag Archives: SelectedOperations

Using Microsoft Graph SelectedOperations Permissions

WIP – work in progress

Initially, *.Selected permissions scope in Graph API only restricted app access to a site collection. Now, it also supports lists, items, folders, and files, and all ‘Selected’ scopes work in both delegated and application modes. This means more granular SharePoint content access for custom apps using the Graph API. Below, I’ll deep-dive into SelectedOperations.Selected permissions and include Python and PowerShell samples for using them.

Client Application

There must be an App Registration for client application that would have access to a SharePoint list.

At this moment (we have a client app and secret, and “” API permissions, but did not provide for this app access to specific sites or libraries) – we should be able to authenticate to Microsoft 365, but not able to get any kind of data (we can get token, but other call to Graph API would return 403 error – Error: b'{“error”:{“code”:”accessDenied”,”message”:”Request Doesn\’t have the required Permission scopes to access a site.”,):

This app registration should have Microsoft Graph “Lists.SelectedOperations.Selected” (or “ListItems.SelectedOperations.Selected” or “Files.SelectedOperations.Selected”) API permissions consented. Registered app Microsoft Graph API permissions should look like:

I use Python console app as a client application. Link to the code at the GitHub is shared below under References, but the core part of the Python code is (I do not use any Microsoft or other libraries here, just plain requests to Microsoft Graph for authentication and for data):

import requests
import json
from secrets import clientSc, clientId, tenantId, siteId, listId 

# specify client id, client secret and tenant id
# clientId = ""
# clientSc = "" 
# tenantId = "" 

apiUri = "https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/token"

body = {
    "client_id"     : clientId,
    "client_secret" : clientSc,
    "scope"         : "https://graph.microsoft.com/.default",
    "grant_type"    : "client_credentials" 
}

try: 
    response = requests.post(apiUri, data=body)
    token = json.loads(response.content)["access_token"]
except:
    print("Error: ", json.loads(response.content)["error_description"])
    exit()

print("Got token: ", token[0:10], "...")
headers={'Authorization': 'Bearer {0}'.format(token)}

# Get specific site list
print("Geting specific site list")
# graph_url = 'https://graph.microsoft.com/v1.0/sites/' + siteId + '/lists/' + listId
graph_url = 'https://graph.microsoft.com/beta/sites/' + siteId + '/lists/' + listId
graphResponse = requests.get(   graph_url, headers=headers )
print(" Response status code: ", graphResponse.status_code)
if graphResponse.status_code == 200:
    list = json.loads(graphResponse.content)
    print(" List display name: ", list["displayName"])

References

Python connect to SharePoint via Graph API with Delegated Permissions

Below is the sample Python code to authenticate against Microsoft 365 as current user with MSA library and to call Microsoft Graph API – specifically get SharePoint Site, get Site lists with requests library.

But first, you have to have an App Registration in Azure (Entra ID) with delegated permissions consented and authentication configured.

Delegated Permissions

If your solution needs access to all SharePoint sites – consider Sites.FullControl.All or Sites.Manage.All or Sites.ReadWrite.All or Sites.Read.All depending on access level you need. Effective permissions would be an intersection (minimum) from both – permissions configured for app registration and permissions current user have. Once consented at the app registration – these permissions will work right away.

If your solution needs access to a one (or a few) SharePoint sites – consider Sites.Selected API permissions as it will scope down access to the only sites that are required for your solution to work. Remember, Sites.Selected API permissions, even consented at the app registration, require second step – SharePoint admin should provide (read or write or manage or fullcontrol) permissions for the app registration to a specific site or sites.

Authentication

You’d also need to configure authentication blade. How? It depends on the kind of application you are building etc. For example for native apps I do:
– add platform – “Mobile and Desktop app”
– select “https://login.microsoftonline.com/common/oauth2/nativeclient”
– select “msal096fd951-7285-4e4f-9c1f-23a393556b19://auth (MSAL only)”
– add custom Redirect URI: “http://localhost”

This config works for Python code below

Python Code

You’d need to install/import the libraries: json, configparser, msal, requests

Here is the code:

import json
import configparser
import msal
import requests

config = configparser.ConfigParser()
config.read('config.cfg')
client_id = config.get('delegated','clientId')
authority = config.get('delegated','authority')
scopes = config.get('delegated','scope').split()
siteId = config.get('delegated','siteId')
print( client_id)
print( authority)
print( scopes)
print( siteId)

global_token_cache = msal.TokenCache()
global_app = msal.PublicClientApplication(
    client_id,
    authority=authority,  # For Entra ID or External ID
    token_cache=global_token_cache,  
    )

def acquire_and_use_token():
    # The pattern to acquire a token looks like this.
    result = None
    result = global_app.acquire_token_interactive(scopes)

    if "access_token" in result:
        print("Token was obtained from:", result["token_source"])  # Since MSAL 1.25
        # print("Token acquisition result", json.dumps(result, indent=2))
        return result["access_token"]
    else:
        print("Token acquisition failed", result)  # Examine result["error_description"] etc. to diagnose error
        return None


token = acquire_and_use_token()


http_headers = {'Authorization': 'Bearer ' + token,
                'Accept': 'application/json',
                'Content-Type': 'application/json'}

graph_url = 'https://graph.microsoft.com/v1.0/sites/' + siteId + '?$select=id,webUrl,displayName'

siteResponse = requests.get(graph_url, headers=http_headers)
print(siteResponse.status_code)
site = json.loads(siteResponse.content)
# print("Site (raw) : ")
# print(site)
print("Site webUrl : ", site["webUrl"])
print("Site displayName : ", site["displayName"])

# Lists
graph_url = 'https://graph.microsoft.com/v1.0/sites/' + siteId + '/lists'
listsResponse = requests.get(graph_url, headers=http_headers)
print(listsResponse.status_code)
lists = json.loads(listsResponse.content)
# print("Site lists (raw):")
# print(lists)
print("Site lists:")
for list in lists["value"]:
    print("  Display Name:", list["displayName"])
    print("   Id:", list["id"])
    print("   Web Url:", list["webUrl"])
    print("   Created Date:", list["createdDateTime"])
    print("   Last Modified Date:", list["lastModifiedDateTime"])

Application permissions

If your scenario is to call Graph API from Python with application permissions (aka unattended or daemon app) – the main difference is authentication. It is described here. It also requires App registration configured like this.

Microsoft Graph SelectedOperations Permissions to SharePoint

Microsoft says “Initially, Sites.Selected existed to restrict an application’s access to a single site collection. Now, lists, list items, folders, and files are also supported, and all Selected scopes now support delegated and application modes.”. In other words, Microsoft started supporting even more granular access to SharePoint content from custom applications using Microsoft Graph API.

In the article below I will deep-dive into SelectedOperations.Selected permissions, including PowerShell scripts to provide granular permissions (if you want to know more about Sites.Selected Graph API permissions – it’s here).

Why do we need SelectedOperations.Selected Graph API permissions

Granular permissions available are:

Lists.SelectedOperations.SelectedProvides application access to a specific list
ListItems.SelectedOperations.SelectedProvides application access to one or more list items, files, or folders
Files.SelectedOperations.SelectedProvides application access to to one or more files or library folders

Set of SelectedOperations permissions is exactly what Microsoft promised a few years ago. And this is great, as we really need granular access to the content in SharePoint sites. I’ve been supporting enterprise SharePoint for more than 15 years now, and I know that it was always a concern if application in fact requires access to a specific list/library or a folder or even one file, but admins provide access to entire site collection.

Especially, I believe, this feature will become more in demand due to Copilot for Microsoft 365. Currently – it’s mostly developers and data analytics who needs unattended application access to SharePoint, but sooner or later regular users powered with m365 Copilot license will start creating autonomous agents…

Here is the screenshot of a Copilot agent authentication/access to SharePoint data using client id and secret:

So below is my research and lab setup, guide with screenshots and PowerShell scripts on how to provide granular (to library/list or folder, or even just one document or list item) Graph API permissions to SharePoint. This KBA is for Microsoft 365 SharePoint administrators. I’m planning to have a separate KBA for developers on how to use granular permissions.

Prerequisites

Admin App

First, we need an Admin App – an app we will be using to provide permissions.

The only requirement to the app is: the app should have Microsoft.Graph Sites.FullControl.All Graph API permissions consented:

Target Site, List. Item

Your client will probably provide you with the link to the SharePoint resource they need access to. But to do both – to provide granular permissions – or to access one specific list, folder or item – we need to know this site id, list id, item id. So it’ll be our admins job to decompose the link and get Ids to provide access, then share these Ids with the client with some instructions on how to call Graph API to get access.

For this lab/demo setup, I have created three sites under Microsoft Teams (group-based Teams-connected SharePoint sites), then test list and test library in each, like this:

Client Application

There must be an App Registration for client application – application that will have access to Test-List-01 and Test-Lib-01 only. This app registration should have Microsoft Graph “Lists.SelectedOperations.Selected” or “ListItems.SelectedOperations.Selected” or “Files.SelectedOperations.Selected” API permissions consented. Example below has Lists:

Providing selectedoperations permissions

PowerShell script to provide selectedoperations.selected access for an app to a specific list would be as below. Here we use plain calls to MS Graph API. Full script for your refence is available at GitHub, but here is the essential part:

$apiUrl = "https://graph.microsoft.com/beta/sites/$targetSiteId/lists/$targetSiteListId/permissions"
$apiUrl 
$params = @{
	roles = @(
	    "read"
    )
    grantedTo = @{
        application = @{
            id = $clientAppClientId
        }
    }
}
$body = $params | ConvertTo-Json
$response = Invoke-RestMethod -Headers $Headers -Uri $apiUrl -Method Post -Body $body -ContentType "application/json"

Notes

  1. (Update from 2025-10-28) SelectedOperations permissions are still in beta. E.g. I have to call “https://graph.microsoft.com/beta/sites/$targetSiteId/lists/$targetSiteListId/permissions”
    When trying to call “/v1.0/sites/$targetSiteId/lists/$targetSiteListId/permissions” it says
    "code": "BadRequest", "message": "Resource not found for the segment \u0027permissions\u0027."
  2. The “/beta/sites/$targetSiteId/lists/$targetSiteListId/permissions” API returns not only applications permissions, but also user’s permissions!
  3. TBD: I’m not sure if it’s a bug or my incorrect setup, but I noticed that if I provide access for the app to the list – app can read site.

TBC…

References

Granular Application Permissions to SharePoint

In 2021 Microsoft implemented “Sites.Selected” Graph API permissions to allow application access (without a signed in user) to specific sites (entire site only). In 2024 Microsoft implemented granular access – to specific list/libraries, as well as to specific documents/files and list items. Now name convention is *.SelectedOperations.Selected.
Permissions come in two flavors – delegated and application:

  • Files.SelectedOperations.Selected – Allow the application to access a subset of files (files explicitly permissioned to the application). The specific files and the permissions granted will be configured in SharePoint Online or OneDrive.
  • ListItems.SelectedOperations.Selected – Allow the application to access a subset of lists. The specific lists and the permissions granted will be configured in SharePoint Online.
  • Lists.SelectedOperations.Selected – Allow the application to access a subset of lists. The specific lists and the permissions granted will be configured in SharePoint Online.

I wrote two articles:


Introduction video from Microsoft: