Blog Post

Apps on Azure Blog
10 MIN READ

Connection Between Web App and O365 Resources: Using SharePoint as an Example

theringe's avatar
theringe
Icon for Microsoft rankMicrosoft
Dec 24, 2024

Microsoft Entra enforced MFA for all user login processes in late 2024. This change has caused some Web Apps using delegated permissions to fail in acquiring access tokens, thereby interrupting communication with other resources.

TOC

  • Introduction
  • [not recommended] Application permission

  • [not recommended] Delegate permission with Device Code Flow
  • Managed Identity
  • Multi-Tenant App Registration
  • Restrict Resources for Application permission
  • References

 

Introduction

In late 2024, Microsoft Entra enforced MFA (Multi-Factor Authentication) for all user login processes. This change has caused some Web Apps using delegated permissions to fail in acquiring access tokens, thereby interrupting communication with O365 resources. This tutorial will present various alternative solutions tailored to different business requirements.

We will use a Linux Python Web App as an example in the following sections.

[not recommended] Application permission

Traditionally, using delegated permissions has the advantages of being convenient, quick, and straightforward, without being limited by whether the Web App and Target resources (e.g., SharePoint) are in the same tenant. This is because it leverages the user identity in the SharePoint tenant as the login user.

However, its drawbacks are quite evident—it is not secure. Delegated permissions are not designed for automated processes (i.e., Web Apps), and if the associated connection string (i.e., app secret) is obtained by a malicious user, it can be directly exploited.

Against this backdrop, Microsoft Entra enforced MFA for all user login processes in late 2024. Since delegated permissions rely on user-based authentication, they are also impacted. Specifically, if your automated processes originally used delegated permissions to interact with other resources, they are likely to be interrupted by errors similar to the following in recent times.

AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '00000003-0000-0000-c000-000000000000'

 

The root cause lies in the choice of permission type. While delegated permissions can technically be used for automated processes, there is a more appropriate option—application permissions, which are specifically designed for use in automated workflows.

Therefore, when facing such issues, the quickest solution is to create a set of application permissions, align their settings with your previous delegated permissions, and then update your code to use the new app ID and secret to interact with the target resource.

This method resolves the issue caused by the mandatory MFA process interruption. However, it is still not entirely secure, as the app secret, if obtained by a malicious user, can be exploited directly. Nonetheless, it serves as a temporary solution while planning for a large-scale modification or refactor of your existing system.

[not recommended] Delegate permission with Device Code Flow

Similarly, here's another temporary solution. The advantage of this approach is that you don't even need to create a new set of application permissions. Instead, you can retain the existing delegated permissions and resolve the issue by integrating Device Code Flow. Let's see how this can be achieved.

First, navigate to Microsoft Entra > App Registration > Your Application > Authentication, and enable "Allow public client flows".

 

Next, modify your code to implement the following method to acquire the token. Replace [YOUR_TENANT_ID] and [YOUR_APPLICATION_ID] with your own values.

import os, atexit, msal, sys

def get_access_token_device():
    cache_filename = os.path.join(
        os.getenv("XDG_RUNTIME_DIR", ""), "my_cache.bin"
    )
    cache = msal.SerializableTokenCache()
    if os.path.exists(cache_filename):
       cache.deserialize(open(cache_filename, "r").read())
    atexit.register(lambda:
       open(cache_filename, "w").write(cache.serialize())
       if cache.has_state_changed else None
    )
    config = {
        "authority": "https://login.microsoftonline.com/[YOUR_TENANT_ID]",
        "client_id": "[YOUR_APPLICATIOM_ID]",
        "scope": ["https://graph.microsoft.com/.default"]
    }
    app = msal.PublicClientApplication(
        config["client_id"], authority=config["authority"],
        token_cache=cache,
    )
    result = None
    accounts = app.get_accounts()
    if accounts:
        print("Pick the account you want to use to proceed:")
        for a in accounts:
            print(a["username"])
        chosen = accounts[0]
        result = app.acquire_token_silent(["User.Read"], account=chosen)
    if not result:
        flow = app.initiate_device_flow(scopes=config["scope"])
        print(flow["message"])
        sys.stdout.flush()
        result = app.acquire_token_by_device_flow(flow)
    if "access_token" in result:
        access_token = result["access_token"]
        return access_token
    else:
        error = result.get("error")
        if error == "invalid_client":
            print("Invalid client ID.Please check your Azure AD application configuration")
        else:
            print(error)

 

Demonstrating the Process

  1. Before acquiring the token for the first time, there is no cache file named my_cache.bin in your project directory.
  2. Start the test code, which includes obtaining the token and interacting with the corresponding service (e.g., SharePoint) using the token.
  3. Since this is the first use, the system will prompt you to manually visit https://microsoft.com/devicelogin and input the provided code. Once the manual process is complete, the system will obtain the token and execute the workflow.
  4. After acquiring the token, the cache file my_cache.bin will appear in your project directory. This file contains the access_token and refresh_token.
  5. For subsequent processes, whether triggered manually or automatically, the system will no longer prompt for manual login.

 

The cached token has a validity period of approximately one hour, which may seem insufficient. However, the acquire_token_silent function in the program will automatically use the refresh token to renew the access token and update the cache. Therefore, as long as an internal script or web job is triggered at least once every hour, the token can theoretically be used continuously.

Managed Identity

Using Managed Identity to enable interaction between an Azure Web App and other resources is currently the best solution. It ensures that no sensitive information (e.g., app secrets) is included in the code and guarantees that only the current Web App can use this authentication method. Therefore, it meets both convenience and security requirements for production environments.

Let’s take a detailed look at how to set it up.

 

Step 1: Setup Managed Identity

You will get an Object ID for further use.

 

Step 2: Enterprise Application for Managed Identity

Your Managed Identity will generate a corresponding Enterprise Application in Microsoft Entra. However, unlike App Registration, where permissions can be assigned directly via the Azure Portal, Enterprise Application permissions must be configured through commands.

 

Step 3: Log in to Azure via CloudShell

Use your account to access Azure Portal, open a CloudShell, and input the following command. This step will require you to log in with your credentials using the displayed code:

Connect-MgGraph -Scopes "Application.ReadWrite.All", "AppRoleAssignment.ReadWrite.All"

Continue by inputting the following command to target the Enterprise Application corresponding to your Managed Identity that requires permission assignment:

$PrincipalId = "<Your web app managed identity object id>"
$ResourceId = (Get-MgServicePrincipal -Filter "displayName eq 'Microsoft Graph'" | Select-Object -ExpandProperty Id)

 

Step 4: Assign Permissions to the Enterprise Application

Execute the following commands to assign permissions. Key Points:

This example assigns all permissions with the prefix Sites.*. However, you can modify this to request only the necessary permissions, such as:

  • Sites.Selected
  • Sites.Read.All
  • Sites.ReadWrite.All
  • Sites.Manage.All
  • Sites.FullControl.All

If you do not wish to assign all permissions, you can change { $_.Value -like "*Sites.*" } to the specific permission you need, for example: { $_.Value -like "*Sites.Selected*" }

Each time you modify the permission, you will need to rerun all the commands below.

$AppRoles = Get-MgServicePrincipal -Filter "displayName eq 'Microsoft Graph'" -Property AppRoles |
Select -ExpandProperty AppRoles |
Where-Object { $_.Value -like "*Sites.*" }
$AppRoles | ForEach-Object {
    $params = @{
        "PrincipalId" = $PrincipalId
        "ResourceId"  = $ResourceId
        "AppRoleId"   = $_.Id
    }
    New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $PrincipalId -BodyParameter $params
}

Step 5: Confirm Assigned Permissions

If, in Azure Portal, you see a screen similar to this: (Include screenshot or example text for granted permissions) This means that the necessary permissions have been successfully assigned.

 

Step 6: Retrieve a Token in Python

In your Python code, you can use the following approach to retrieve the token:

from azure.identity import ManagedIdentityCredential

def get_access_token():
    credential = ManagedIdentityCredential()
    token = credential.get_token("https://graph.microsoft.com/.default")
    return token.token

Important Notes:

When permissions are assigned or removed in the Enterprise Application, the ManagedIdentityCredential in your Python code caches the token for a while.

These changes will not take effect immediately. You need to restart your application and wait approximately 10 minutes for the changes to take effect.

 

Step 7: Perform Operations with the Token

Finally, you can use this token to perform the desired operations. Below is an example of creating a file in SharePoint:

You will notice that the uploader’s identity is no longer a person but instead the app itself, indicating that Managed Identity is indeed in effect and functioning properly.

While this method is effective, it is limited by the inability of Managed Identity to handle cross-tenant resource requests. I will introduce one final method to resolve this limitation.

 

Multi-Tenant App Registration

In many business scenarios, resources are distributed across different tenants. For example, SharePoint is managed by Company (Tenant) B, while the Web App is developed by Company (Tenant) A. Since these resources belong to different tenants, Managed Identity cannot be used in such cases.

 

Instead, we need to use a Multi-Tenant Application to resolve the issue.

 

The principle of this approach is to utilize an Entra ID Application created by the administrator of Tenant A (i.e., the tenant that owns the Web App) that allows cross-tenant use. This application will be pre-authorized by future user from Tenant B (i.e., the administrator of the tenant that owns SharePoint) to perform operations related to SharePoint.

 

It should be noted that the entire configuration process requires the participation of administrators from both tenants to a certain extent. Please refer to the following demonstration.

 

This is a sequential tutorial; please note that the execution order cannot be changed.

 

Step 1: Actions Required by the Administrator of the Tenant that Owns the Web App

1.1. In Microsoft Entra, create an Enterprise Application and select "Multi-Tenant." After creation, note down the Application ID.

 

1.2. In App Registration under AAD, locate the previously created application, generate an App Secret, and record it.

 

1.3. Still in App Registration, configure the necessary permissions. Choose "Application Permissions", then determine which permissions (all starting with "Sites.") are needed based on the actual operations your Web App will perform on SharePoint. For demonstration purposes, all permissions are selected here.

 

Step 2: Actions Required by the Administrator of the Tenant that Owns SharePoint

2.1. Use the PowerShell interface to log in to Azure and select the tenant where SharePoint resides.

az login --allow-no-subscriptions --use-device-code

 

2.2. Add the Multi-Tenant Application to this tenant.

az ad sp create --id <App id get from step 1.1>

 

2.3. Visit the Azure Portal, go to Enterprise Applications, locate the Multi-Tenant Application added earlier, and navigate to Permissions to grant the permissions specified in step 1.3.

 

Step 3: Actions Required by the Administrator of the Tenant that Owns the Web App

3.1. In your Python code, you can use the following method to obtain an access token:

from msal import ConfidentialClientApplication

def get_access_token_cross_tenant():
    tenant_id = "your-sharepoint-tenant-id"  # Tenant ID where the SharePoint resides (i.e., shown in step 2.1)
    client_id = "your-multi-tenant-app-client-id"  # App ID created in step 1.1
    client_secret = "your-app-secret"  # Secret created in step 1.2
    authority = f"https://login.microsoftonline.com/{tenant_id}"

    app = ConfidentialClientApplication(
        client_id,
        authority=authority,
        client_credential=client_secret
    )

    scopes = ["https://graph.microsoft.com/.default"]
    token_response = app.acquire_token_for_client(scopes=scopes)
    return token_response.get("access_token")

 

3.2. Use this token to perform the required operations.

Restrict Resources for Application permission

Application permission, allows authorization under the App’s identity, enabling access to all SharePoint sites within the tenant, which could be overly broad for certain use cases.

 

To restrict this permission to access a limited number of SharePoint sites, we need to configure the following settings:

 

Actions Required by the Administrator of the Tenant that Owns SharePoint

  1. During the authorization process, only select Sites.Selected. (refer to Step 4 from Managed Identity, and Step 1.3 from Multu-tenant App Registration)
  2. Subsequently, configure access separately for different SharePoint sites.

 

During the process, we will create a temporary App Registration to issue an access token, allowing us to assign specific SharePoint sites' read/write permissions to the target Application. Once the permission settings are completed, this App Registration can be deleted.

 

Refer to the above images, we need to note down the App Registration's object ID and tenant ID. Additionally, we need to create an app secret and grant it the Application permission Sites.FullControl.All. Once the setup is complete, the token can be obtained using the following command.

$tenantId = "<Your_Tenant_ID>"
$clientId = "<Your_Temp_AppID>"
$clientSecret = "<Your_Temp_App_Secret>"
$scope = "https://graph.microsoft.com/.default"
$url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$body = @{
    grant_type    = "client_credentials"
    client_id     = $clientId
    client_secret = $clientSecret
    scope         = $scope
}
$response = Invoke-RestMethod -Uri $url -Method Post -Body $body
$accessToken = $response.access_token

 

Before granting the write permission to the target application, even if the Application Permission already has the Sites.Selected scope, an error will still occur.

 

Checking the current SharePoint site's allowed access list shows that it is empty.

$headers = @{
    "Authorization" = "Bearer $accessToken"
    "Content-Type"  = "application/json"
}
Invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/v1.0/sites/<Your_SharePoint_Site>.sharepoint.com" -Headers $headers

 

Next, we manually add the corresponding Application to the SharePoint site's allowed access list and assign it the write permission.

$headers = @{
    "Authorization" = "Bearer $accessToken"
    "Content-Type"  = "application/json"
}
$body = @{
    roles = @("write")
    grantedToIdentities = @(
        @{
            application = @{
                id = "<Your_Target_AppID>"
		displayName = "<Your_Target_AppName>"
            }
        }
    )
    grantedToIdentitiesV2 = @(
        @{
            application = @{
                id = "<Your_Target_AppID>"
		displayName = "<Your_Target_AppName>"
            }
        }
    )
} | ConvertTo-Json -Depth 10
Invoke-RestMethod -Method Post -Uri "https://graph.microsoft.com/v1.0/sites/<Your_SharePoint_Site>.sharepoint.com/permissions" -Headers $headers -Body $body

 

Rechecking the current SharePoint site's allowed access list confirms the addition.

 

After that, writing files to the site will succeed, and you could delete the temp App Registration.

References

Updated Dec 26, 2024
Version 4.0
No CommentsBe the first to comment