Hi @Olivia Chen,
You can leverage an Azure Function with a configured managed identity to access a SharePoint document library. To do so:
- Enable a system-assigned managed identity for Azure Function, you can follow the steps mentioned in https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=portal%2Cdotnet#add-a-system-assigned-identity. This will create an app registration in your tenant.
- Grant that identity the necessary permissions to access the SharePoint document library. In Entra Id, search for the app registration, select API Permissions > SharePoint > and select the permission type and roles needed. The following PowerShell script does the same thing.
- Use the Microsoft Graph API to access the document library in your Function app. You can use the
requests
Python module to make the request. This uses the local function itself to retrieve it's identity token that you use to set the HTTP Authorization header in the request to SharePoint.
import requests
import pandas as pd
# Replace <tenant-id>, <site-id>, <document-library-id>, and <file-name> with your values
url = f"https://graph.microsoft.com/v1.0/sites/<tenant-id>:/sites/<site-id>:/drives/<document-library-id>/root:/{file-name}:/workbook/tables('Sheet1')/rows"
# Get an access token using the managed identity of the Azure Function
identity_endpoint = "http://169.254.169.254/metadata/identity/oauth2/token"
identity_header = {"Metadata": "true"}
identity_params = {
"resource": "https://graph.microsoft.com/",
"api-version": "2018-02-01"
}
identity_response = requests.get(identity_endpoint, headers=identity_header, params=identity_params)
access_token = identity_response.json()["access_token"]
# Make a GET request to the Microsoft Graph API to read the Excel file as a pandas dataframe
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
data = response.json()["value"]
df = pd.DataFrame(data)
I did come across the following blog post, https://learningbydoing.cloud/blog/connecting-to-sharepoint-online-using-managed-identity-with-granular-access-permissions/, which someone did using a logic app. I think a logic app would be better in this case, but it depends on your decision making that led you to a function app in the first place. Some users did run into issues, https://learn.microsoft.com/en-us/answers/questions/1196213/how-to-grant-permission-to-azure-managed-identity, but still worth checking out.