将服务主体与 Fabric API for GraphQL 配合使用

按照 “连接应用程序 ”部分中的步骤提供对用户主体的访问权限。 还可以使用服务主体访问 GraphQL API:

  1. 按照 连接应用程序 中的步骤创建 Microsoft Entra 应用,但请记住,服务主体不需要作用域。 在新应用中,在 “证书和机密”下添加客户端密码。 有关详细信息,请参阅 注册 Microsoft Entra 应用并创建服务主体

  2. 确保租户管理员允许在 Fabric 中使用服务主体。 在“租户管理员”门户中,转到“租户设置”。 在“开发人员设置”下,启用“服务主体可以使用 Fabric API”。 启用此设置后,应用程序会显示在 Fabric 门户中的角色或权限分配。 可以找到有关标识支持的详细信息。

  3. 服务主体实体需要访问 GraphQL API 和数据源,更具体地说,需要对 GraphQL API 拥有执行权限,以及在所选数据源中相应所需的读取或写入权限。 在 Fabric 门户中,打开工作区并选择 API 旁边的省略号。 选择 API 的“管理权限”,然后选择“添加用户”。 添加应用程序并选择运行查询和突变,这会为服务主体提供所需的执行权限。 出于测试目的,实现对 API 和数据源的所需权限的最简单方法是将应用程序添加为具有参与者角色的工作区成员,GraphQL API 和数据源项都位于该工作区中。

GraphQL API 权限的屏幕截图。

由于服务主体需要证书或客户端密码,因此单页应用程序(MSAL)中的Microsoft身份验证库(MSAL)不支持它,如上一步中生成的 React 应用。 可以根据要求和用例,使用妥善定义的授权逻辑正确保护后端服务。

将 API 配置为可由服务主体访问后,可以在本地计算机上使用简单的 Node.JS 应用程序在本地对其进行测试:

const { ClientSecretCredential } = require('@azure/identity');

// Define your Microsoft Entra ID credentials
const tenantId = "<YOUR_TENANT_ID>";
const clientId = "<YOUR_CLIENT_ID>";
const clientSecret = "<YOUR_CLIENT_SECRET>"; // Service principal secret value

const scope = "https://api.fabric.microsoft.com/.default"; // The scope of the token to access Fabric

// Create a credential object with service principal details
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);

// Function to retrieve the token
async function getToken() {
    try {
        // Get the token for the specified scope
        const tokenResponse = await credential.getToken(scope);
        console.log("Access Token:", tokenResponse.token);
    } catch (err) {
        console.error("Error retrieving token:", err.message);
    }
}

使用所选 Node.js 包管理器安装依赖项(@azure/identity),使用所需的信息修改文件,保存并执行它(node <filename.js>)。 这会从 Microsoft Entra 检索令牌。

然后,可以通过将相应的详细信息替换为检索到的 令牌 、要执行的 GraphQL 查询 和 GraphQL API 终结点,从而使用 PowerShell 调用 GraphQL API API

$headers = @{
    Authorization = "Bearer <YOUR_TOKEN>"
    'Content-Type' = 'application/json'
}

$body = @{
    query = @"
    <YOUR_GRAPHQL_QUERY>
"@
}

# Make the POST request to the GraphQL API
$response = Invoke-RestMethod -Uri "<YOUR_GRAPHQL_API_ENDPOINT>" -Method POST -Headers $headers -Body ($body | ConvertTo-Json)

# Output the response
$response | ConvertTo-Json -Depth 10 

或者,使用 cURL 来实现相同的结果:

curl -X POST <YOUR_GRAPHQL_API_ENDPOINT> \
-H "Authorization: <YOUR_TOKEN>" \
-H "Content-Type: application/json" \
-d '{"query": "<YOUR_GRAPHQL_QUERY(in a single line)>"}'

对于本地测试,请使用额外的依赖项axios()稍微修改 Node.js 代码以检索令牌并在单个执行中调用 API:

const { ClientSecretCredential } = require('@azure/identity');
const axios = require('axios');

// Microsoft Entra ID credentials
const tenantId = "<YOUR_TENANT_ID>";
const clientId = "<YOUR_CLIENT_ID>";
const clientSecret = "<YOUR_CLIENT_SECRET>"; // Service principal secret value

// GraphQL API details
const graphqlApiUrl = "YOUR_GRAPHQL_API_ENDPOINT>";
const scope = "https://api.fabric.microsoft.com/.default"; // The scope to request the token for

// The GraphQL query
const graphqlQuery = {
  query: `
  <YOUR_GRAPHQL_QUERY>
  `
};

// Function to retrieve a token and call the GraphQL API
async function fetchGraphQLData() {
  try {
    // Step 1: Retrieve token using the ClientSecretCredential
    const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
    const tokenResponse = await credential.getToken(scope);
    const accessToken = tokenResponse.token;

    console.log("Access token retrieved!");

    // Step 2: Use the token to make a POST request to the GraphQL API
    const response = await axios.post(
      graphqlApiUrl,
      graphqlQuery,
      {
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'Content-Type': 'application/json'
        }
      }
    );

    // Step 3: Output the GraphQL response data
    console.log("GraphQL API response:", JSON.stringify(response.data));
    
  } catch (err) {
    console.error("Error:", err.message);
  }
}

// Execute the function
fetchGraphQLData();