Before we can make a call to Microsoft 365 from our code – we need to be authenticated. There are many kinds of authentication flows that Microsoft supports. For more details – please refer to Microsoft Identity Platform documentation but in short – there are two major kind of authentications – as a current user and as a daemon application and in both cases we need an application to be registered in Azure.
Briefly here is what you need to have for your custom application to authenticate to Microsoft 365:
configure Secrets or Certificates (for daemon apps)
Register Application in Microsoft Azure
1. You’d go to https://portal.azure.com/ 2. Type app registration in search and select App registration
Update (July 2025) – the search for “App reg” is not working… But you can go to App registrations from Entra Id:
3. Select “New registration”
4. For now, you’d just need to provide your application display name and leave other fields as default – Single tenant and no redirection Url, then click “Register”
5. If you are seeing an error message telling that your are not allowed to register an app – you’d reach your AAD/EntraId/Global admins so they can register an app for you.
6. Under Azure Portal App Registrations you should be able to see your app:
7. Under Overview blade notice you Client Id and tenant Id:
Configure Authentication blade for interactive apps
Azure apps for interactive authentication are configured differently (check MS app types and authentication flows) for different scenarios/platforms.
Here is a good article from MS. Microsoft Graph quick start can register an app for you. Microsoft publish tutorials for .net, Go, Java, JavaScript, PHP, Python, TypeScript…
In a few words, you’d need to add Platform as below
manually if you know how to configure it. Otherwise, Quickstart and/or Integration assistant might help you.
You do not need Certificates or Secrets for authentication as current user.
Configure Secrets or Certificates for daemon apps
Daemon apps (aka service apps, also called background jobs) – all kind unattended access scenarios do not require configuration under Authentication blade – but require Secrets or Certificate. You’d need to be familiar with certificates, as certificates considered as more secure way to authenticate and some authentication flows allow secrets, but some require certificates.
So for daemon apps you need a secret and/or certificate:
Here is how I configure daemon app for PowerShell.
Having an app configured as above – you should be able to authenticate against Microsoft 365 Graph API, but should not have access to resources, as app is not authorized yet.
Why do we need to implement search in our applications?
Use-cases for search on behalf of current user
Along with the usual ones – where you just need your app to search for some data and bring it to user – there is one different scenario I’d like to share:
You need to quickly detect content in SharePoint that is open for everyone
Brute force solution – getting detailed permissions report for all SharePoint sites might not be a feasible option, especially in large environments – it is a very resource-consuming task and might take days and weeks. So consider the following…
Since search is security-trimmed – a user can get only search results he/she already has access to; but what if we create an account and do not grant any SharePoint permissions or group memberships to this account, and then we’d search for everything on behalf of this account? That would mean that all what search returns represent content that is shared with everyone. There are some tricks and gotchas – here is the separate article on the same.
Use-cases for unattended search
What are the use-cases when you need to search in your daemon app or background job? Be aware that when you search on behalf of application credentials – search is NOT security-trimmed and your query would run against ALL SharePoint content… Here are some possible scenarios.
Content detection/Investigation
Let say you want some data is never shared with anyone and never appeared in search for anyone
Or you might want to investigate what is the location some specific data is available at
Imagine you are building sites classification system and you use indexed custom site properties – so you are able to refine search results based on site metadata to get list of specific sites (adaptive scopes used in retention policy are based on the same mechanics)
Automation – let say you have a requirement to configure every tenant site in some ways – for instance – add some hosts to allowed domains to embed video or set some site properties based on who created the site or activate or deactivate some features and so on – how would you do that? You’d probably have a scheduled job that runs let say every hour against only new sites – sites created during that last hour. How would you get these recently created sites? Search with Graph API is the only nice solution today.
In the articles below I’m sharing my techniques on searching in Microsoft 365 SharePoint and Teams from application using Microsoft Graph API. Specifically I’m covering
Microsoft Graph search API
Microsoft.Graph PowerShell module
PnP.PowerShell module
In two flavors:
Search on behalf of currently authenticated user
Unattended Search with daemon (also called service) applications
Below is how do I search Microsoft 365 content programmatically from PowerShell using MS Graph API, PowerShell PnP, Microsoft Graph module, MSAL library being authenticated as user or daemon application. Let me focus on SharePoint content here but you can use the same technique to search through other Microsoft 365 services. Also, I’ll be using PowerShell but same ideas should work for other platforms/languages – Python, C#, node.js etc.
To search on behalf of currently authenticated user we need delegated “Sites.Read.All” API permissions. I recommend you to add both Graph API and SharePoint API permissions as different libraries might use different API’s under the hood. Ensure you add delegated “Sites.Read.All” even if you already have “Sites.FullControl.All” as by some reason “Sites.FullControl.All” does not always work for search.
Here is how an app API permissions to search as current user should look like:
For unattended search – e.g. search on behalf of daemon app – we need application “Sites.Read.All” API permissions. Again, I suggest both Graph API and SharePoint API permissions added. Here is how an app API permissions to search as daemon app should look like:
Ensure you got admin consent for API permissions.
In case you have incorrect permissions in your app – Microsoft Graph will be kind enough to inform you exactly what you need. Example:
“Access to ChatMessage in Graph API requires the following permissions: Chat.Read or Chat.ReadWrite, ChannelMessage.Read.All. However, the application only has the following permissions granted: Sites.Read.All, User.Read”
Assuming we have configured apps – let us get started with
Microsoft Graph API
Microsoft Graph API allows search through all the Microsoft 365 content – including Exchange e-mail messages, Yammer (Viva Engage) and Teams chat messages and surely OneDrive and SharePoint content (please refer to the original doc).
Authenticate as current user to Search with Graph API
I use MSAL.PS PowerShell module to get token, then I build a headers variable
If you are getting error message “SearchRequest Invalid (Region is required when request with application permission.)”:
that’s OK, just modify your body to include region like this (“region”: “NAM” for North America or “GBR” or …). Also, I can modify body with from/size for paging (technique used to iterate through search results if there are many) and return just specific fields to decrease traffic and improve performance:
For daemon app authentication we need a certificate configured in Azure App and installed on the user machine. Daemon app authentication code sample (please specify your tenant id, app (client) id and certificate thumbprint:
Microsoft recently (Oct 2023) announced Microsoft Graph command-line interface (CLI) tool – mgc. Microsoft: “The Microsoft Graph PowerShell command-line interface (CLI) acts as an API wrapper for the Microsoft Graph APIs, exposing the entire API set for use from the command line”. Example:
mgc users list --filter "displayName eq 'John Smith'"
Meantime there is a Microsoft Graph PowerShell SDK (PowerShell module Microsoft.Graph ) since 2020. Example:
Get-MgUser -Filter "displayName eq 'John Smith'"
So, what is the difference? Why Microsoft provides two similar tools? What are the use case scenarios, functionality and scope of each one?
You administer Microsoft 365 SharePoint Online. Part of your daily activities is providing Microsoft Graph and SharePoint Sites.Selected API permissions to other users (developers).
In Aug/Sep 2023 Microsoft pushed an update that prevents site collection admins to create or update an Azure Access Control (ACS) principal (that was the way most of developers used to get Client Id and Client secret to access SharePoint site). So your users are probably getting something like Your SharePoint tenant admin doesn’t allow site collection admins to create or update an Azure Access Control (ACS) principal message attempting to create or update SharePoint App-only principal at AppRegNew.aspx or AppInv.aspx pages. Here are more details on the issue.
Microsoft and MVPs shared some technique how to provide Sites.Selected API permissions, but dealing with scripts manually, elevating individual permissions every time you need to run the script – it all takes time and not very efficient. More and more devs are reaching you on the app. So you want to automate this process.
SharePoint list as a frontend here you can accept intake requests, organize approval workflow and display automation results
Azure Function App as a backend here will be your PowerShell script hosted that runs on scheduled basis and takes care of actual permissions provisioning
Solution details
High-level, getting application permissions to some specific SharePoint site is a two-step process:
get application registration in Azure and properly configure it
get permissions for this application to a specific SharePoint site
For the first step – check this and this articles. I’ll focus on the second step below.
You can provide Sites.Selected permissions for the app to a site with
I will be using second one one. Also PnP.PowerShell will be used to get access to SharePoint intake site and read/update requests from SharePoint list and so on.
Azure App Registration
I registered an admin Application in Azure – “SharePoint Automation App”, added Graph Sites.FullControl.All and SharePoint Sites.FullControl.All permissions, then added Microsoft Graph Directory.Read.All permissions and got tenant admin consent:
I generated a self-signed certificate and added it to the app:
This app will be used to call provide permissions, and to connect to the SharePoint front-end.
Users will register their applications in Azure, add Graph Sites.Selected and SharePoint Sites.Selected permissions, got tenant admin consent, then request permissions to the specific site by creating an intake request – new list item.
Front-End SharePoint Site
I created a SharePoint site for automation. This site will play a front-end role for users. I created a list “Sites.Selected” and updated list columns so I have the following fields:
Target Site Url
Application Id
Permissions (read/write)
Automation Output
In real-world (Prod) – You can (should) also implement approval workflow as you’d provide permissions for the application to the site only with this site owner approval. The PowerShell code behind should also validate site owner’s consent with app access to site. But for the sake of simplicity I’ll skip this in my demo.
Azure Function App
I created an Azure Function App with the following parameters: – Runtime stack: PowerShell Core – Version: 7.2. – OS: Windows – Hosting plan: Consumption
And then PowerShell timer-triggered function in Visual Studio Code.
Function requirements.psd1 (it takes a few hours for Azure to install modules; while modules are installing – you might see “[Warning] The first managed dependency download is in progress, function execution will continue when it’s done. Depending on the content of requirements.psd1, this can take a few minutes. Subsequent function executions will not block and updates will be performed in the background.”):
@{
'Az' = '10.*'
'PnP.PowerShell' = '2.*'
}
Azure Az module to access other Azure resources. PnP.PowerShell module will be used to access SharePoint.
I will keep my admin Azure registered app in a key vault, so need somehow to let the key vault know that this specific app can access this specific credentials. So I enabled system assigned managed Identity for the Function App:
MS: “This resource is registered with Azure Active Directory. The managed identity can be configured to allow access to other resources…”. I’m going to use an object (principal) Id of this function to grant access to keyvault.
Azure key vault
Surely we do not hard-code app secrets. So we need a key vault o store app credentials.
I created a key vault under the same resource group in Azure and named it “SharePointAutomationDemo”. Then I added a roles assignment – “Key Vault Secret User” and “Key vault Reader” to the Function App via it’s managed identity:
I also assigned “Key Vault Administrator” role to the user (developer) who will add certificates/secrets to this key vault and develop Azure function code.
With the new ‘Lists.SelectedOperations.Selected’, ‘ListItems.SelectedOperations.Selected’ and ‘Files.SelectedOperations.Selected’ permissions it is new possible to provide application permissions at a specific list, library or list item levels or at a particular document level, so automation solution would be a little more complicated.
getOffice365GroupsActivityDetail – details about Microsoft 365 groups and activity
getSharePointSiteUsageDetail – details about SharePoint sites and usage
getTeamsTeamActivityDetail – details about Microsoft Teams and activity by teams
Also we know, that Teams sites are group-based, and you can have private and shared channels under Teams – but these sites are not actually group-based and there are group-based SharePoint sites with no Teams behind.
And activities might be different – update document or just visit home page, provide permissions and update channel properties etc.
So the question is what kind of activity at what level is recorded at which report?
So far what I noticed is
If there were activities in Teams or SharePoint – the corresponding group will be included in Groups Activity report as well.
I analyzed sites activities as part of inactive sites decommissioning – and I found out that most of “active” group-based sites that have one or two in “active SharePoint files” under Groups Activity report are not really active. In many cases that activity is just OD sync or site logo read from desktop applications (word, excel) – with no actual documents reading/updating or teams activity. So consider “visited pages” from SharePoint Site Usage Detail report or “read messages” from Teams Activity report as a stronger indicator of activity.
As SharePoint or Teams admin you manage Microsoft 365 groups (create, update, delete, manage membership etc.) having your admin role activated. I prefer PowerShell 7 and Microsoft.Graph PowerShell module, and I need an Azure registered app with “Group.ReadWrite.All” Microsoft Graph API delegated permission.
Some findings:
If a user was not a group member or group owner – and the user is added to the group members – this user will get notification “You’ve joined the <Group Name> group” via e-mail that comes from a group e-mail address.
When a user is added to the group owners (or elevated to group owner if user was a group member) – user does not get notification.
When a user was a group owner and now you are adding this user to the group members – user does not get notification.
All the actions are logged into Microsoft 365 audit log under your personal Id.
Script samples:
# This script is just a sample to demonstrate basic technique on getting, updating groups membership and deletion m365 groups with PowerShell and MS Graph
#
# please do not run this script as is, but update it based on your needs
# authentication with personal Id
# app must have as minimum "Group.ReadWrite.All" Microsoft Graph API delegated permission
# user must have SharePoint admin (or Teams admin) roles activated
Connect-MgGraph -ClientId $clientid -TenantId $tenantId
Get-MgContext | Select-Object Scopes -ExpandProperty Scopes
# sample data
$groups = @()
$groups += [PSCustomObject]@{GroupId = '443d22ae-683a-4fe4-8875-7bd78227a026' }
$groups += [PSCustomObject]@{GroupId = 'e5805388-c18c-48c0-b42d-6223cf8f3d82' }
# Get Groups
foreach ($group in $groups) {
Get-MgGroup -GroupId $group.GroupId
}
# add members to the group
$groupId = '443d22ae-683a-4fe4-8875-7bd78227a026'
$userId = 'df74e0d3-d78c-495b-b47a-549437d93cf7' # Adele
New-MgGroupMember -GroupId $groupId -DirectoryObjectId $userId
# add Owner to the group
$groupId = '443d22ae-683a-4fe4-8875-7bd78227a026'
$userId = 'eacd52fb-5ae0-45ec-9d17-5ded9a0b9756' # Megan
New-MgGroupOwner -GroupId $groupId -DirectoryObjectId $userId
# Delete group
$groupId = '443d22ae-683a-4fe4-8875-7bd78227a026'
Remove-MgGroup -GroupId $groupId
Sites.Selected permissions are required to get access to only one or a few specific SharePoint sites using Microsoft Graph API and/or SharePoint API (since Microsoft announced the EOL of SharePoint App-only service principals, Sites.Selected is the only option going forward). Below are
Historically, we utilized so-called SharePoint app-only service principals to get unattended (daemon/service) access to one specific site programmatically. Initially in on-premises, later in SPO. We used to get SharePoint app-only service principals via appregnew.aspx and provide permissions via the appinv.aspx page. SharePoint app-only principals allow calls to SharePoint (REST) API and usage of SharePoint CSOM via ACS-based authentication.
Then Microsoft started developing Graph API. You’d need to register your app in Azure to get App ID and App Secret to authenticate to Microsoft Graph API. You’d also configure specific API permissions for this app to get access to services you need (SharePoint, Exchange, Teams etc.). Unfortunately, for a long time there were no options to get access to only one specific site with Graph API. Available API permissions (e.g. Sites.Read.All) allowed access to all SharePoint sites in the tenant.
Then, in 2021 Microsoft introduced Graph API “Sites.Selected” application permissions. Hooray! But the problem was developers needed to have two service principals – new Sites.Selected to call Graph API and classic SP-App-only to call SharePoint API. Later, in 2022 Microsoft added SharePoint “Sites.Selected” API permissions – so both APIs are available for a single App Id (more App-Only and Sites.Selected history details…).
Long story short, below are the detailed steps to configure Sites.Selected for you unattended app access to SharePoint site.
Steps to get and configure Sites.Selected permissions
1. Register an application in Azure (Entra Id) via Azure portal GUI, PowerShell script or helpdesk/servicedesk request. E.g. with GUI you’d login to portal.azure.com, then “Entra Id” -> “App registrations” and select “+ New registration”:
If you are not allowed to register an Entra Id app due to restrictions in your company – connect with your IT/admins, as there must me some way to request an app.
Once you get an application registration and you are this app owner – you should be able to navigate to your app registration in Azure Portal and configure it (Step 2 below).
2. “API permissions” – you’d need both – MS Graph API Sites.Selected and SharePoint Sites.Selected application API permissions configured (as libraries/modules and 3-rd party software can use both APIs under the hood):
Then you’d request tenant admin consent for your API permissions. Finally your app registration “API permissions” should look like:
3. App Secret or Certificate Under Certificates and secrets – generate client secret, copy secret value to safe location. Or you can get a certificate (obtain trusted or create self-signed), and upload it to your app registration. Certificates are considered as more secure option.
4. At the Overview page – grab your app client id and tenant id :
At this moment, having tenant id, app (client) id and client secret (or certificate) – you should be able to authenticate to Microsoft 365 tenant with app-only authentication flow, but will not be able to access any resource.
Having just Sites.Selected API permissions configured for the app does not mean your app has access to any SharePoint site automatically. Access to a specific site for the app is granted by the SharePoint team via another Graph API call. That leads us to the next step.
5. Application access to SharePoint site You need to request this from your SharePoint service admin (or if you are an admin – DIY), but access needs to be provided for the specific app to the specific site with specified permissions: Read-Only or Read/Write or Manage or Full Control. – Here is the Graph API – Here is PowerShell PNP cmdlet
Write role is similar to “Contributor” user permissions – it allows CRUD operations against list items (library documents and metadata)
Manage role allows create/update/delete lists/libraries
FullControl is full control
At this moment you should be able to access SharePoint sites. How? See below:
Use Sites.Selected permissions
Once your SharePoint tenant/service admin confirmed that access has been provided for you app to a specific SharePoint site/sites – you can use the app client id and client secret (or certificate) to work with SharePoint from your code using MS Graph API or SharePoint API. The exact technique depends on the language/platform you use, but there are some good tutorials published:
Generally, these Sites.Selected permissions allow you to make calls that are documented under “Files” and “Sites and Lists” Graph API documentation. I.e. get site details, get site lists/libraries, create lists and libraries, CRUD operations against list items, download/upload library documents – all within the specific site. Sites.Selected permissions do not allow search operations, anything related to groups or teams etc.
If you are facing issues – first of all, try to isolate the issue – are permissions to blame, or is it something else? To ensure permissions for your app were provided correctly – you can validate your app access to the target SharePoint site with simple PowerShell scripts: here is the sample code
Important Note: Sites.Selected API permissions allow you to call Microsoft Graph API with client Id and client secret or certificate. Calling SharePoint API with a client secret is not supported. You have to use a certificate to call SharePoint API.
Calls to SharePoint API with client Id and client secret are possible only if ACS-based permissions are provided for the app to the site (with appinv.aspx), which is strongly discouraged due to the announced retirement of App-Only (ACS) – see updates in the end of the article.
Secure your credentials
You should not hard-code your secret as you do not want your credentials to be leaked. So you need to secure your secrets in production. Solutions for secrets are included in cloud providers’ offerings, you can also use environment variables. If you are hosting your application in Azure – consider using key vault to store your secrets. You can configure managed identity for your application and provide access to the key vault for you application’s managed id. (Actually, if your app is running in Azure – it is possible to provide permissions for your app directly – via managed identity. This is considered as an even more secure setup – no app registration and no Key Vault is needed, as there are no credentials to store, but that’s a separate story: Connecting to Microsoft 365 and Graph API from the Azure Function App via Managed Identity).
Govern Sites.Selected permissions
(For SharePoint admins).
Existing admins API/cmdlets allow yo to provide Sites.Selected permissions for specific app to specific site, and to get Sites.Selected permissions provided to the specific site. But there is no API/cmdlet for the specific app to get all sites (with permissions) this app has access to. Meantime as SharePoint admin if you keep providing permissions upon users/devs requests – after some time you have no idea what app has access to what site with what level of access, especially in large organizations. Surely you can (and should) pull reports on all registered apps with access to SharePoint, but…
There is a solution developed by Joe Rodgers (Microsoft). This solution use SharePoint list as an inventory/storage and Power Automate flows to pull data from Entra Id and SharePoint and provides kind of dashboard so you can review details of all app registrations in the tenant with at SharePoint Online permission. Cool!
Also, if you have a licensed Copilot for Microsoft 365 – you have a license for SharePoint Advanced Management (SAM). And under SAM – Reports – you have aт “App insights” report, that tells you how various non-Microsoft applications registered to your Microsoft Entra Id access your SharePoint content (report is based on the Microsoft 365 audit log).
Note: you would not provide Sites.Selected permissions just upon user/developer request. You’d always get an approval from the target site owner. The site owner must understand that application will have permanent unattended access to the entire SharePoint site with permissions specified (read or write or manage or full control).
Generally, to provide an Application with Sites.Selected API permissions configured access to a specific site, SharePoint admin would run a set of PowerShell commands (or C# program or…) to ensure the client id exists, API permissions are configured and consented, to get app owners, target site owners, to get existing app permissions etc. Finally, admin would provide permissions and validate that permissions were provided correctly. It does not take long…
Update: Microsoft announced ACS permissions (app-only principals) retirement in 2026. So using ACS for any new development is not recommended.
It may be acceptable to grant ACS permissions to existing legacy custom applications or third-party or Microsoft apps/web apps (e.g. Alteryx, Azure Data Factory) – applications that only support a client ID and secret and use the SharePoint API under the hood – but only to avoid disruption to business processes and keeping in mind that ACS will expire soon, so these applications must be replaced/updated before 2026.
Update: Microsoft is implementing granular (permissions to list, item or file) alongside with Sites.Selected permissions. Original implementations of Sites.Selected allowed access to entire site collection only. With new ‘Lists.SelectedOperations.Selected’, ‘ListItems.SelectedOperations.Selected’ and ‘Files.SelectedOperations.Selected’ permissions it is possible to provide application permissions to list, library or list item or particular document (reference).
Let say you need to run some code against Microsoft 365 on a scheduled basis. For this, you can use Azure Function App and timer-triggered Functions. From the code you’d call Microsoft Graph API and/or SharePoint API, so you’d need your Function somehow to get credentials on the fly from the KV and use it to call APIs. For this – you’d have a key vault where credentials will be be stored and retrieved by functions when needed. How does KV know if it’s ok to share secrets with the function app? Below I’ll share step-by-step how to create, configure and secure an Azure Function with system-assigned managed identity, and Azure Key Vault.
Below is a “classic” approach with client id, client secret and a key vault.
First, we’ll create a resource group, e.g. “Azure-Func-Secured”.
Next, we’ll create a function app:
We’ll avoid the default “Flex Consumption” service plan (as it is Linux-only and does not support dependencies) and select “Consumption” a hosting option for now:
Runtime stack we’ll be using is PowerShell Core 7.4, but you can choose your own (options are – Python, .Net (C#), Node.js, Java). Let us leave other configuration settings by default (e.g. Enable Public access: On) for now, we’ll fix (secure) it later.
Ok, the function app has been created. Notice that app service plan, application insights and storage account, as well as some other services were created automatically under the same resource group:
Now we can create one or more functions under this function app, also we’d need to create a key vault and a registered app. Let us start with function and VS Code would be our environment of choice.
Let us start Visual Studio Code in a separate folder. Ensure you have “Azure Functions”, “Azure Resources” and PowerShell extensions by Microsoft. You’d sign-in to Azure:
and create a function project:
You’d choose “Timer triggered” function (as we need the function running on schedule), the function name would be MyScheduledFunct01 and we’d leave the default schedule as “0 */5 * * * *” – so our function will be triggered every 5 minutes.
Let us deploy the function right away and see if it works. For this, we can use “deploy” icon under “WORKSPACE” panel:
or “Deploy to function app” option from the function app context pop-up menu under the Azure “RESOURCES” panel:
After successful deployment give it some time, then check function invocations and ensure function is triggered an running:
Next, we’d update “requirements.psd1” to include Azure Key Vault and PnP PowerShell modules as it takes some time for the function app to pull in and install dependencies. Requirements.psd1:
# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
# For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. Uncomment the next line and replace the MAJOR_VERSION, e.g., 'Az' = '5.*'
# 'Az' = 'MAJOR_VERSION.*'
'Az.KeyVault' = '6.*'
'PnP.PowerShell' = '2.*'
}
And we’d update function itself to monitor if dependencies are installed, than we’d deploy the function again so time would work for us. MyScheduledFunction/run.ps1:
# Input bindings are passed in via param block.
param($Timer)
$currentUTCtime = (Get-Date).ToUniversalTime()
if ($Timer.IsPastDue) {
Write-Host "PowerShell timer is running late!"
}
Write-Host "PowerShell timer trigger function ran! TIME: $currentUTCtime"
#############################################################################################
Write-Host "Check modules installed:"
Import-Module PnP.PowerShell
Import-Module Az.KeyVault
Get-Module PnP.PowerShell
Get-Module Az.KeyVault
Write-Host "Check command available:"
Get-Command -Name Connect-PnPOnline -Module PnP.PowerShell
At first, we might see warning like “The first managed dependency download is in progress, function execution will continue when it’s done. Depending on the content of requirements.psd1, this can take a few minutes. Subsequent function executions will not block and updates will be performed in the background.”. So we’d just wait.
After some time the function will be able to use required modules. Here is the invocation output example:
App Registration To get unattended access to SharePoint (or Teams or Exchange etc.) as a service (daemon) application – we need credentials. It is done via “App Registration” under Entra Id (Azure AD) – here is the detailed step-by-step guide on registering apps in Azure.
Finally, we’d have a service principal with permissions we need:
We do not hard-code secrets, so let us create a key vault to keep secrets safe:
We’d leave all other configuration option by default, including “Azure role-based access control”, Allow access from: All Networks etc.
Here is the trick: even if I created this key vault and have an admin-level access, I’m not able to work with secrets values. So I need to provide additional access to myself. Being at the key vault, navigate to “Access control (IAM)” and add role assignment…
We’d select “Key Vault Secrets Officer”, next, select members… and select own name:
From this moment you should be able to CRUD secrets with values.
Now, let us generate a secret under App registration and copy secret value:
Then navigate to the Key Vault -> Object/Secrets -> Generate/Import – and save the secret value there:
Now you can get this secret… but the function cannot reach the secret… Here is the proof. Let us update the function code with:
and check the function output. You’d see something like (which is not very descriptive):
ERROR: Run Connect-AzAccount to login. Exception : Type : System.Management.Automation.PSInvalidOperationException ErrorRecord : Exception : Type : System.Management.Automation.ParentContainsErrorRecordException Message : Run Connect-AzAccount to login. HResult : -2146233087 CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException FullyQualifiedErrorId : InvalidOperation TargetSite : Name : get_DefaultContext DeclaringType : [Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet] MemberType : Method Module : Microsoft.Azure.PowerShell.Clients.ResourceManager.dll Message : Run Connect-AzAccount to login. Source : Microsoft.Azure.PowerShell.Clients.ResourceManager HResult : -2146233079 StackTrace : at Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet.get_DefaultContext() at Microsoft.Azure.Commands.KeyVault.Models.KeyVaultCmdletBase.get_DataServiceClient() at Microsoft.Azure.Commands.KeyVault.GetAzureKeyVaultSecret.ExecuteCmdlet() at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__31.<ExecuteSynchronouslyOrAsJob>b__3_0(T c) at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action1 executor) at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet) at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord() CategoryInfo : CloseError: (:) [Get-AzKeyVaultSecret], PSInvalidOperationException FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.GetAzureKeyVaultSecret InvocationInfo : MyCommand : Get-AzKeyVaultSecret ScriptLineNumber : 19 OffsetInLine : 13 HistoryId : 1 ScriptName : C:\home\site\wwwroot\myScheduledFunction\run.ps1 Line : $kvSecret = Get-AzKeyVaultSecret -VaultName $vaultName -Name $secretName -AsPlainText Statement : Get-AzKeyVaultSecret -VaultName $vaultName -Name $secretName -AsPlainText PositionMessage : At C:\home\site\wwwroot\myScheduledFunction\run.ps1:19 char:13 + $kvSecret = Get-AzKeyVaultSecret -VaultName $vaultName -Name $secretN … + ~~~~~~~~~~~~~ PSScriptRoot : C:\home\site\wwwroot\myScheduledFunction PSCommandPath : C:\home\site\wwwroot\myScheduledFunction\run.ps1 InvocationName : Get-AzKeyVaultSecret CommandOrigin : Internal ScriptStackTrace : at , C:\home\site\wwwroot\myScheduledFunction\run.ps1: line 19 PipelineIterationInfo : 0 1
So, how’d we allow key vault access for the function app? It’s as simple as that: – first, we’d need some identity assigned to function app – second, we’d provide access to the key vault to this identity
Managed Identity: assign an identity to the function. For this, you’d go to function Settings/Identity, and under System Assigned, you’d switch status to On and Save settings.
Then, you’d go to your key vault, Access Control (IAM) and add role assignment. But this time, you’d select the role “Key Vault Secrets User” (more about roles), and “Assign access to” Managed Identity, and select members – select your function app identity (notice, identity is assigned to function app, so all functions under the app will be able to use the identity):
Now, we’d check the next function invocation detail, and voila:
You can see that azure function was able on the fly to pull secret from the key vault, so now we should be able to use these credentials to access SharePoint.
As you know, having client id and client secret would allow you to call MS Graph API. But calling SharePoint API would require authentication with a certificate. “PnP.PowerShell” module use both APIs under the hood, so we’d need a certificate to connect to tenant and work with SharePoint using “PnP.PowerShell” module. Please refer to this article on how to run Connect-PnPOnline with Certificate stored in the Key Vault.
Securing Azure Function
Out-of-the-box Azure Function App is created in a not very secure manner. Here is whan we’d need to do to secure Azure Functions:
Finally, it’d be more secure not to have a key vault, but provide permissions to the managed identity of the Azure Function App.