Поделиться через


Overview of workload authentication guidelines in Microsoft Fabric

В этой статье содержатся рекомендации по работе с проверкой подлинности при создании рабочих нагрузок Microsoft Fabric. В ней содержатся сведения о работе с токенами и согласиями.

Before you begin, make sure you're familiar with the concepts in Authentication overview and Authentication setup.

Data plane and control plane APIs

  • Data plane APIs are APIs that the workload backend exposes. The workload frontend can call them directly. For data plane APIs, the workload backend can decide on what APIs to expose.

  • Control plane APIs are APIs that go through Fabric. The process starts with the workload frontend calling a JavaScript API, and it ends with Fabric calling the workload backend. Примером такого API является создание элемента.

    For control plane APIs, the workload must follow the contracts defined in the workload backend and implement those APIs.

Expose an API tab on the workload's application in Microsoft Entra ID

On the Expose an API tab, you need to add scopes for control plane APIs and scopes for data plane APIs:

  • The scopes added for control plane APIs should preauthorize the Fabric Client for Workloads application with application ID d2450708-699c-41e3-8077-b0c8341509aa. Those scopes are included in the token that the workload backend receives when Fabric calls it.

    You need to add at least one scope for the control plane API for the flow to work.

  • The scopes added for data plane APIs should preauthorize Microsoft Power BI with application ID 871c010f-5e61-4fb1-83ac-98610a7e9110. Они содержатся в токене, который возвращает API JavaScript acquireAccessToken.

    For data plane APIs, you can use this tab to manage granular permissions for each API that your workload exposes. В идеале вам следует добавить набор разрешений для каждого API, который раскрывает серверная часть рабочей нагрузки, и проверить, что полученный токен включает эти разрешения, когда эти API вызываются с клиента. Например:

    • Рабочая нагрузка открывает два API для клиента, ReadData и WriteData.
    • The workload exposes two data plane scopes, data.read and data.write.
    • In the ReadData API, the workload validates that the data.read scope is included in the token before it continues with the flow. То же самое относится к WriteData.

API permissions tab on the workload's application in Microsoft Entra ID

On the API permissions tab, you need to add all the scopes that your workload needs to exchange a token for. Обязательной областью для добавления является Fabric.Extend в службе Power BI. Requests to Fabric might fail without this scope.

Working with tokens and consents

When you're working with data plane APIs, the workload frontend needs to acquire a token for calls to the workload backend.

The following sections describe how the workload frontend should use the JavaScript API and on-behalf-of (OBO) flows to acquire tokens for the workload and external services, and to work with consents.

Шаг 1. Получение токена

Рабочая нагрузка начинается с запроса токена с использованием JavaScript API без предоставления параметров. This call can result in two scenarios:

  • The user sees a consent window of all the static dependencies (what's configured on the API permissions tab) that the workload configured. Этот сценарий происходит, если пользователь не является частью домашнего клиента приложения, и пользователь не предоставил согласие Microsoft Graph для этого приложения раньше.

  • Пользователь не видит окно согласия. Этот сценарий происходит, если пользователь уже предоставил согласие на использование Microsoft Graph по крайней мере один раз для этого приложения, или если пользователь является частью домашнего арендатора приложения.

В обоих сценариях рабочая нагрузка не должна принимать во внимание, дал ли пользователь полное согласие для всех зависимостей (и не может знать это на данном этапе). The received token has the workload backend audience and can be used to directly call the workload backend from the workload frontend.

Шаг 2. Попробуйте получить доступ к внешним службам

Для рабочей нагрузки может потребоваться доступ к службам, которым требуется проверка подлинности. For that access, it needs to perform the OBO flow, where it exchanges the token that it received from its client or from Fabric to another service. The token exchange might fail because of lack of consent or some Microsoft Entra Conditional Access policy that's configured on the resource that the workload is trying to exchange the token for.

To solve this problem, it's the workload's responsibility to propagate the error to the client when working with direct calls between the frontend and the backend. It's also the workload's responsibility to propagate the error to the client when working with calls from Fabric by using the error propagation described in Workload communication.

После распространения ошибки рабочая нагрузка может вызвать API JavaScript acquireAccessToken для решения проблемы с политикой согласия или условного доступа и повторить операцию.

Сведения об ошибках API уровня данных см. в разделе Обработка многофакторной аутентификации, условного доступа и добавочного согласия. For control plane API failures, see Workload communication.

Примеры сценариев

Рассмотрим рабочую нагрузку, необходимую для доступа к трем API Fabric:

  • List workspaces: GET https://api.fabric.microsoft.com/v1/workspaces

  • Create a warehouse: POST https://api.fabric.microsoft.com/v1/workspaces/{workspaceId}/warehouses

  • Write to a lakehouse file: PUT https://onelake.dfs.fabric.microsoft.com/{filePath}?resource=file

To be able to work with those APIs, the workload backend needs to exchange tokens for the following scopes:

  • Для перечисления рабочих областей: https://analysis.windows.net/powerbi/api/Workspace.Read.All или https://analysis.windows.net/powerbi/api/Workspace.ReadWrite.All
  • Для создания склада: https://analysis.windows.net/powerbi/api/Warehouse.ReadWrite.All или https://analysis.windows.net/powerbi/api/Item.ReadWrite.All
  • For writing to a lakehouse file: https://storage.azure.com/user_impersonation

Note

You can find scopes needed for each Fabric API in this reference article.

Области, упомянутые ранее, необходимо настроить в приложении рабочей нагрузки в соответствии с разрешениями API .

Рассмотрим примеры сценариев, с которыми может столкнуться рабочая нагрузка.

Example 1

Let's assume that the workload backend has a data plane API that gets the workspaces of the user and returns them to the client:

  1. Фронтенд рабочей нагрузки запрашивает токен с помощью JavaScript API.

  2. The workload frontend calls the workload backend API to get the workspaces of the user and attaches the token in the request.

  3. The workload backend validates the token and tries to exchange it for the required scope (let's say https://analysis.windows.net/powerbi/api/Workspace.Read.All).

  4. Рабочая нагрузка не смогла обменять токен для указанного ресурса, так как пользователь не дал приложению согласия на доступ к этому ресурсу (см. коды ошибок AADSTS).

  5. Серверная часть системы управления нагрузкой передает ошибку пользовательскому интерфейсу, сообщив, что необходимо согласие для этого ресурса. The workload frontend calls the acquireAccessToken JavaScript API and provides additionalScopesToConsent:

    workloadClient.auth.acquireAccessToken({additionalScopesToConsent: ["https://analysis.windows.net/powerbi/api/Workspace.Read.All"]})

    Кроме того, рабочая нагрузка может принять решение о предоставлении согласия для всех статических зависимостей, настроенных в приложении, поэтому он вызывает API JavaScript и предоставляет promptFullConsent:

    workloadClient.auth.acquireAccessToken({promptFullConsent: true}).

Этот вызов запрашивает окно согласия независимо от того, предоставил ли пользователь согласие на некоторые зависимости. После этого интерфейс управления рабочей нагрузкой может повторить операцию.

Note

Если обмен маркерами по-прежнему завершается ошибкой согласия, это означает, что пользователь не предоставил согласие. Рабочая нагрузка должна обрабатывать такие сценарии; Например, уведомите пользователя о том, что этот API требует согласия и не будет работать без него.

Example 2

Let's assume that the workload backend needs to access OneLake on the Create Item API (call from Fabric to the workload):

  1. The workload frontend calls the Create Item JavaScript API.

  2. Серверная часть рабочей нагрузки получает вызов из Fabric, извлекает делегированный токен и проверяет его.

  3. The workload tries to exchange the token for https://storage.azure.com/user_impersonation but fails because the tenant administrator of the user-configured multifactor authentication needed to access Azure Storage (see AADSTS error codes).

  4. The workload propagates the error alongside the claims returned in the error from Microsoft Entra ID to the client by using the error propagation described in Workload communication.

  5. The workload frontend calls the acquireAccessToken JavaScript API and provides claims as claimsForConditionalAccessPolicy, where claims refers to the claims propagated from the workload backend:

    workloadClient.auth.acquireAccessToken({claimsForConditionalAccessPolicy: claims})

After that, the workload can retry the operation.

Handling errors when requesting consents

Иногда пользователь не может предоставить согласие из-за различных ошибок. После запроса согласия ответ возвращается на URI перенаправления. В нашем примере этот код отвечает за обработку ответа. (Его можно найти в файле index.ts.)

const redirectUriPath = '/close'; 
const url = new URL(window.location.href); 
if (url.pathname?.startsWith(redirectUriPath)) { 
    // Handle errors, Please refer to https://learn.microsoft.com/entra/identity-platform/reference-error-codes 
    if (url?.hash?.includes("error")) { 
        // Handle missing service principal error 
        if (url.hash.includes("AADSTS650052")) { 
            printFormattedAADErrorMessage(url?.hash); 
        // handle user declined the consent error 
        } else  if (url.hash.includes("AADSTS65004")) { 
            printFormattedAADErrorMessage(url?.hash); 
        } 
    } 
    // Always close the window  
    window.close(); 
} 

Интерфейс рабочей нагрузки может извлечь код ошибки из URL-адреса и обрабатывать его соответствующим образом.

Note

In both scenarios (error and success), the workload must always close the window immediately, with no latency.