Tag Archives: Managed Identity

A managed identity is an id that can be assigned to a supported Azure resource. Once a managed identity is assigned, it can be authorized to access other Azure or MS Graph API or Microsoft 365 resources.

Connecting to Microsoft 365 and Graph API from the Azure Function App via Managed Identity

There is a well-known and well-documented way of connecting to Microsoft 365 SharePoint and Graph API from Azure Function App via keeping credentials (Client id and client secret) in the Azure Key Vault. In this article I explained how to configure Azure Key Vault so Azure Function can get credential and use them to access Microsoft 365 SharePoint and call Graph API. For this to work we need an App registration with permissions provided. But what if we assign permissions directly to the Function App?
As per Microsoft, managed identities enable Azure resources to authenticate to cloud services (e.g. Azure Key Vault) without storing credentials in code. Is it possible to use function managed identity to access Microsoft 365 SharePoint via PnP or Graph API? Follow me.

I assume we already have an Entra Id, a Microsoft 365 subscription in it and an Azure subscription in the same tenant.

Create a User Assigned Managed Identity

There are two types of managed identities in Azure – System assigned and user assigned.
If you go to Azure Function app -> Settings -> Identity – you’ll see these two options:

  • System assigned Managed Identity will be created automatically if you select Status:On and Save. Having System-assigned Managed Identity you can provide permissions to Azure resources (e.g. storage, key vault) to this specific instance of function app. If you create another function app that’d need the same access – you’d need to enable system assigned Managed Identity again, for this new instance and again provide permissions.
  • User assigned managed identity is created as standalone Azure resource, and will have it’s own lifecycle. A single Azure resource (e.g. Function App) can utilize multiple user assigned managed identities. Similarly, a single user assigned managed identity can be shared across multiple resources. So if you deploy another Function App that need the same permissions as your existing function app – you’d just assign the same managed identity to this new function app.

So before we assign a user-assigned managed identity to a resource, we need to create a user-assigned managed identity:

For the Name of your User Assigned Managed Identity consider something that would uniquely identify you (your team) and your project/app at tenant level, e.g. “m365-Enterprise-SharePoint-Engineering-Managed-Identity-Demo”:

Create and Configure a Function App

Create your function app as you usually do that. (If you want to kill two birds with one stone – create a function app with “App Service” – aka Dedicated plan – you’ll see how to secure your function app storage account access with Managed Identity).

I use PowerShell Core as runtime stack and Windows.

Once Function App is created – we need to create a function. I’ll do it via Azure Portal for simplicity and I’ll select timer-triggered function:

Ensure that this function works ootb correctly by triggering test run:

Then we’d need to assign a managed identity earlier created to this function app.
Navigate to Function App -> Settings -> Identity, select “User Assigned” and managed identity:

Disable Az

Navigate to Function App -> Functions -> App Files. Select “profile.ps1”.
Remove or comment out part that use Az module cmdlets:

Update function dependencies

Since I use PowerShell and PnP for this demo, I need PnP module loaded.
Navigate to Function App -> Functions -> App Files. Select “requirements.psd1”. Update your code by adding ‘PnP.PowerShell’ = ‘2.12.0’ to the required modules. Do not enable Az module:

It takes time for the function app to download and install PnP module so you can use it in functions.

Update function code

Add the following code to function:

# My custom code
Write-Host "My custom code started"
$siteUrl = "https://contoso.sharepoint.com/sites/Test101/"
$adminUrl = "https://contoso-admin.sharepoint.com"
$UserAssignedManagedIdentityObjectId = "b0bfe72c-73a9-4072-a78b-391e9670f4b9"

Write-Host "Connecting as admin..."
$connectionAdmin = Connect-PnPOnline -Url $adminUrl -ManagedIdentity -UserAssignedManagedIdentityObjectId $UserAssignedManagedIdentityObjectId -ReturnConnection -ValidateConnection
Write-Host "ConnectionAdmin:" $connectionAdmin.Url
Write-Host "Getting tenant site as admin..."
$site = Get-PnPTenantSite -Identity $siteUrl -connection $connectionAdmin
Write-Host "Got site:" $site.Url
Write-Host "Getting admin site..."
$site = Get-PnPSite -connection $connectionAdmin
Write-Host "Got site:" $site.Url

Now you can Test/run the function or wait 5 minutes, then check what is in logs. You should see, that

  1. connection ran successfully, but
  2. getting site failed with “ERROR: The remote server returned an error: (401) Unauthorized.”

And that is ok, as

  1. With Connect-PnPOnline we are authenticating. And since managed id exist – we were recognized
  2. Our managed Id does not have any permissions yet, so any request will fail

Now it’s time to provide actual permissions for the managed identity to the site.

Grant permissions for the managed identity to access SharePoint via Graph API

Here is the most interesting part – somehow we need to provide our user assigned managed identity with permissions to access SharePoint (or any other Microsoft 365 service) via Microsoft Graph API and/or SharePoint API. We already know how to grant permissions to an App Registration in Azure – there is a GUI for that. But with respect to managed identity – there is no GUI. It’s done via Microsoft Graph API or PowerShell. And we need admin permissions to assign roles to a managed identity.

Who can grant roles to a managed identities

It says a Global Admin permissions required to provide roles to a managed identity.

As usual, there are two options: delegated permissions and application permissions (here is where differences explained). In both cases you’d need an App Registration with the following API permissions assigned and consented :

  • Application.Read.All (or higher)
  • AppRoleAssignment.ReadWrite.All

If you have an app with delegated permissions – you’d need a Global admin role to be activated. Or you need an app with application permissions configured as below:

If you are getting something like this:

That means you configured an app incorrectly.

Assigning permissions with Microsoft Graph API:

tbp…

Assigning permissions with PnP PowerShell

Here is the code:

$Id = "..." # User Assigned Managed Identity Object Id = Principal Id
Get-PnPAzureADServicePrincipalAssignedAppRole -Principal $Id 
$role = "Sites.FullControl.All"
Add-PnPAzureADServicePrincipalAppRole -Principal $Id -AppRole $role -BuiltInType MicrosoftGraph
Add-PnPAzureADServicePrincipalAppRole -Principal $Id -AppRole $role -BuiltInType SharePointOnline

Issues found

What I found is that connection to a specific site does not work, .i.e. the following code:

$siteUrl = "https://jvkdev.sharepoint.com/sites/Test101/"
$UserAssignedManagedIdentityObjectId = "b0bfe72c-73a9-4072-a78b-391e9670f4b9"
Write-Host "Connecting to a specific site..."
$connectionSite = Connect-PnPOnline -Url $siteUrl -ManagedIdentity -UserAssignedManagedIdentityObjectId $UserAssignedManagedIdentityObjectId -ReturnConnection
Write-Host "ConnectionSite:" $connectionSite.Url
Write-Host "Getting site..."
$site = Get-PnPSite -connection $connectionSite
Write-Host "Got site:" $site.Url

returns [Error] ERROR: The remote server returned an error: (401) Unauthorized.

Update: it’s probably just a matter of time… After some hours the same code started working well.
Though here Microsoft says “To ensure that changes to permissions for managed identities take effect quickly, we recommend that you group Azure resources using a user-assigned managed identity with permissions applied directly to the identity”

Sites.Selected

Would everything above work if we need to provide access for the function app user assigned managed identity to a specific SharePoint site via Sites.Selected?

It works! I used a separate user-assigned managed identity, provided it with Sites.Selected API permissions, provided access for the managed identity to a specific site and it worked!

PnP.PowerShell version

Is there a difference in behavior of PnP.PowerShell v2 and v3? Let us see…

As for now, it works with both versions – PnP.PowerShell 2.12.0 and PnP.PowerShell 3.1.0

References

Connecting to Microsoft 365 SharePoint and Graph API from Azure Function App

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.

Update: you can make it even more secure – you can assign permissions directly to function, eliminating credentials and key vault. I created a KBA: Connecting to Microsoft 365 and Graph API from the Azure Function App via Managed Identity

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:

Write-Host "Get secret from the key vault:"
$vaultName = "azure-func-secrets"
$secretName = "azure-func-secured-01"
$kvSecret = Get-AzKeyVaultSecret -VaultName $vaultName -Name $secretName -AsPlainText
Write-Host "Secret:" $kvSecret.Substring(0,3)

and check the function output. You’d see something like (which is not very descriptive):

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.

References: