Fabric 擴充性工具包提供一個 JavaScript API,用於取得認證權杖,可用於存取 Fabric API、Azure 服務及任何 Entra 安全應用程式。 本文提供完整的 API 參考與使用範例。
小提示
欲快速入門指南,請參閱 「取得 Microsoft Entra 代幣」。
API 參考資料
acquireFrontendAccessToken(params: AcquireFrontendAccessTokenParams): Promise<AccessToken>;
export interface AcquireFrontendAccessTokenParams {
scopes: string[];
}
export interface AccessToken {
token: string;
}
備註
目前的擴充性工具包實作支援基本的令牌擷取與作用域。 進階功能如完全同意提示與條件存取處理尚未提供,但未來版本可能會加入。
API 回傳一個 AccessToken 包含以下內容的物件:
- 標記:用於授權標頭的 JWT 標記字串
基本用法
簡單代幣取得
// Acquire a token with default Fabric permissions
const token = await workloadClient.auth.acquireFrontendAccessToken({ scopes: [] });
// Use the token in API calls
const response = await fetch('https://api.fabric.microsoft.com/v1/workspaces', {
headers: {
'Authorization': `Bearer ${token.token}`,
'Content-Type': 'application/json'
}
});
具有特定範圍的代幣
// Request specific scopes for Azure Storage
const token = await workloadClient.auth.acquireFrontendAccessToken({
scopes: ['https://storage.azure.com/user_impersonation']
});
代幣使用範例
Fabric API 存取
該憑證可直接與 Fabric REST API 一起使用:
async function listWorkspaces() {
const token = await workloadClient.auth.acquireFrontendAccessToken({ scopes: [] });
const response = await fetch('https://api.fabric.microsoft.com/v1/workspaces', {
headers: {
'Authorization': `Bearer ${token.token}`
}
});
return await response.json();
}
Azure service access
使用範圍來指定你需要存取的 Azure 服務:
async function readFromStorage(accountName, containerName, blobName) {
const token = await workloadClient.auth.acquireFrontendAccessToken({
scopes: ['https://storage.azure.com/user_impersonation']
});
const url = `https://${accountName}.blob.core.windows.net/${containerName}/${blobName}`;
const response = await fetch(url, {
headers: {
'Authorization': `Bearer ${token.token}`,
'x-ms-version': '2021-12-02'
}
});
return await response.text();
}
自訂應用程式存取
存取您自己的 Entra 保護應用程式:
async function callCustomAPI() {
const token = await workloadClient.auth.acquireFrontendAccessToken({
scopes: ['https://myapp.contoso.com/data.read']
});
const response = await fetch('https://myapp.contoso.com/api/data', {
headers: {
'Authorization': `Bearer ${token.token}`
}
});
return await response.json();
}
參數參考
scopes
一組範圍字串陣列,用來指定你的令牌所需的權限。
常見的 Azure 服務範圍:
-
https://storage.azure.com/user_impersonation- Azure 儲存 -
https://vault.azure.net/user_impersonation- Azure Key Vault -
https://management.azure.com/user_impersonation- Azure 資源管理器 -
https://graph.microsoft.com/User.Read- Microsoft 圖譜
使用範例:
const token = await workloadClient.auth.acquireFrontendAccessToken({
scopes: [
'https://storage.azure.com/user_impersonation'
]
});
空作用域陣列: 使用空陣列取得帶有預設 Fabric 權限的令牌:
const token = await workloadClient.auth.acquireFrontendAccessToken({ scopes: [] });
同意管理
自動同意流程
擴充性工具包自動處理同意工作流程:
- 初步請求:若缺少同意,會跳出視窗
- 使用者互動:使用者授予或拒絕權限
- 自動關閉:彈出視窗在使用者操作後自動關閉
- 代幣交付:若成功,代幣會退還給你的應用程式
同意彈出視窗處理
工具包會自動管理同意彈出視窗,但你可以自訂重定向 URI 的行為。 建立一個處理同意回應的重定向頁面:
// redirect.js - Handle consent redirect
const redirectUriPath = '/close';
const url = new URL(window.location.href);
if (url.pathname?.startsWith(redirectUriPath)) {
// Handle consent errors
if (url?.hash?.includes("error")) {
// Extract error information
const errorMatch = url.hash.match(/error=([^&]+)/);
const errorDescription = url.hash.match(/error_description=([^&]+)/);
// Handle specific errors
if (url.hash.includes("AADSTS650052")) {
console.error("Service principal not configured");
} else if (url.hash.includes("AADSTS65004")) {
console.error("User declined consent");
}
}
// Always close the popup immediately
window.close();
}
跨租戶同意
跨租戶存取資源:
// Request consent for cross-tenant access
const token = await workloadClient.auth.acquireAccessToken({
additionalScopesToConsent: ['https://api.partner-app.com/data.read']
});
錯誤處理
常見錯誤案例
async function robustTokenAcquisition() {
try {
return await workloadClient.auth.acquireAccessToken();
} catch (error) {
switch (error.code) {
case 'user_cancelled':
console.log('User cancelled the consent dialog');
break;
case 'consent_required':
console.log('Additional consent required');
break;
case 'interaction_required':
console.log('User interaction required');
break;
default:
console.error('Authentication error:', error.message);
}
throw error;
}
}
憑證到期處理
class TokenManager {
private currentToken: AccessToken | null = null;
async getValidToken(): Promise<AccessToken> {
if (!this.currentToken || this.isTokenExpired(this.currentToken)) {
this.currentToken = await workloadClient.auth.acquireAccessToken();
}
return this.currentToken;
}
private isTokenExpired(token: AccessToken): boolean {
// Add buffer time to prevent requests with almost-expired tokens
const bufferMinutes = 5;
const expirationWithBuffer = new Date(token.expiresOn.getTime() - (bufferMinutes * 60 * 1000));
return new Date() >= expirationWithBuffer;
}
}
最佳做法
令牌快取與重複使用
- 快取標記:將標記儲存在記憶體中直到到期
- 自動更新:在過期前實現自動令牌更新
- 安全儲存:切勿將代幣持久化至本地儲存或 Cookie
範圍管理
- 最小範圍:只請求你需要的權限
- 漸進式同意:隨著功能使用,請求額外範圍
- 範圍驗證:驗證憑證在 API 呼叫前包含必要的範圍
進階錯誤處理
- 優雅降級:當認證失敗時提供備援功能
- 使用者訊息:清楚說明為何需要權限
- 重試邏輯:針對暫態故障實作適當的重試機制
效能優化
- 平行請求:盡可能並行取得多個服務的令牌
- 批次操作:群組 API 呼叫以減少令牌取得負擔
- 快取管理:實施高效的代幣快取策略
相關內容
- 快速入門:取得 Microsoft Entra 代幣 - 簡易入門指南
- 認證概述 - 高階認證概念
- 認證指引 -最佳實務與建議
- Access Fabric API - 預先建構的 API 包裝器