Microsoft Fabric 工作負載中的遠端端點使用專門的認證機制,提供使用者上下文與應用程式身份。 本文說明如何為處理工作、生命週期通知及其他後端操作的遠端端點實作認證。
認證流程概述
Fabric 工作負載包含三個主要的認證流程:
- Fabric 轉 Workload - Fabric 會以 SubjectAndAppToken 格式呼叫你的遠端端點
- 工作負載與 Fabric - 您的工作負載會使用 SubjectAndAppToken 或 Bearer 令牌來呼叫 Fabric API
- 工作負載前端到後端 - 你的前端用承載標記呼叫後端
本文重點在於驗證 Fabric 向您的工作負載發出的請求,並進行返回給 Fabric 的驗證過的呼叫。
SubjectAndAppToken 格式
當 Fabric 呼叫你的遠端端點(用於工作、生命週期通知或其他操作)時,它會使用一種稱為 SubjectAndAppToken 的雙權杖認證格式。
授權標頭結構
SubjectAndAppToken1.0 subjectToken="<user-delegated-token>", appToken="<app-only-token>"
此格式包含兩個不同的標記:
-
subjectToken- 代表執行操作的使用者的委派令牌 -
appToken- 來自 Fabric 應用程式的應用程式專用令牌,證明請求源自 Fabric
這很重要
subjectToken 並不總是存在。 在以下情境中,可能會缺少:
- 服務主體操作 - 當服務主體在沒有使用者上下文的情況下與 Fabric 公共 API 互動
- 系統操作 ——像是項目刪除,且沒有使用者直接參與
- 自動化工作流程 -CI/CD 管線或排程作業,無需使用者互動即可運行
你的遠端端點必須設計成能同時處理兩種情況:有使用者上下文的請求(subjectToken 存在)和沒有使用者上下文的請求(缺少 subjectToken)。
為什麼要用雙代幣?
雙代幣方式有三大主要優點:
- 驗證 - 透過驗證 appToken 來驗證請求是否來自 Fabric
- 使用者上下文 - subjectToken 提供執行動作的使用者上下文
- Inter-Service 通訊 - 使用 subjectToken 取得 On-Behalf-Of(OBO) 標記,用於呼叫具有使用者上下文的其他服務
解析 SubjectAndAppToken
你的遠端端點必須解析授權標頭,才能擷取兩個權杖。
JavaScript 範例
/**
* Parse SubjectAndAppToken from Authorization header
* @param {string} authHeader - Authorization header value
* @returns {object|null} Parsed tokens or null if invalid format
*/
function parseSubjectAndAppToken(authHeader) {
if (!authHeader || !authHeader.startsWith('SubjectAndAppToken1.0 ')) {
return null;
}
const tokenPart = authHeader.substring('SubjectAndAppToken1.0 '.length);
const tokens = {};
const parts = tokenPart.split(',');
for (const part of parts) {
const [key, value] = part.split('=');
if (key && value) {
// Remove surrounding quotes from the token value
const cleanValue = value.trim().replace(/^"(.*)"$/, '$1');
tokens[key.trim()] = cleanValue;
}
}
return {
subjectToken: tokens.subjectToken || null,
appToken: tokens.appToken || null
};
}
使用範例
const authHeader = req.headers['authorization'];
const tokens = parseSubjectAndAppToken(authHeader);
if (!tokens || !tokens.appToken) {
return res.status(401).json({ error: 'Invalid authorization header' });
}
// Now you have access to:
// - tokens.subjectToken (user-delegated token, may be null)
// - tokens.appToken (Fabric app token, always present)
// Check if user context is available
if (tokens.subjectToken) {
console.log('Request has user context');
} else {
console.log('Request is app-only (no user context)');
}
令牌驗證
兩個代幣都必須驗證,以確保真實性及正確的主張。
應用程式令牌驗證
這是 appToken Fabric 的應用程式專用代幣。 驗證:
- Token signature - 驗證 Azure AD 簽章金鑰
-
代幣壽命 - 檢查
nbf(非過期前)及exp(過期)理賠 - 受眾 - 必須與你的工作負載應用程式註冊相符
- Issuer - 必須來自 Azure AD 且租戶正確
-
idtyp聲明 - 必須是"app"僅用於應用程式的代幣 -
無
scp聲明 - 僅限應用程式用代幣沒有範圍聲明 - 租戶識別 碼 - 必須與你的出版商租戶識別碼相符
appToken 聲明範例:
{
"aud": "api://localdevinstance/aaaabbbb-0000-cccc-1111-dddd2222eeee/Fabric.WorkloadSample/123",
"iss": "https://sts.windows.net/12345678-77f3-4fcc-bdaa-487b920cb7ee/",
"iat": 1700047232,
"nbf": 1700047232,
"exp": 1700133932,
"appid": "11112222-bbbb-3333-cccc-4444dddd5555",
"appidacr": "2",
"idtyp": "app",
"oid": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
"tid": "bbbbcccc-1111-dddd-2222-eeee3333ffff",
"ver": "1.0"
}
主體令牌驗證
使用者委派的代幣是 subjectToken。 驗證:
- Token signature - 驗證 Azure AD 簽章金鑰
-
代幣壽命 - 檢查
nbf與exp聲明 - 受眾 - 必須與你的工作負載應用程式註冊相符
- Issuer - 必須來自 Azure AD 且租戶正確
-
scp申請 - 必須包含"FabricWorkloadControl"範圍 -
無
idtyp主張 權 - 委派代幣沒有此權利 -
appid必須匹配 - 應該和 appToken 一樣
subjectToken 主張範例。
{
"aud": "api://localdevinstance/aaaabbbb-0000-cccc-1111-dddd2222eeee/Fabric.WorkloadSample/123",
"iss": "https://sts.windows.net/12345678-77f3-4fcc-bdaa-487b920cb7ee/",
"iat": 1700050446,
"nbf": 1700050446,
"exp": 1700054558,
"appid": "11112222-bbbb-3333-cccc-4444dddd5555",
"scp": "FabricWorkloadControl",
"name": "john doe",
"oid": "bbbbbbbb-1111-2222-3333-cccccccccccc",
"upn": "user1@contoso.com",
"tid": "bbbbcccc-1111-dddd-2222-eeee3333ffff",
"ver": "1.0"
}
JavaScript 令牌驗證範例
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');
/**
* Validate Azure AD token
* @param {string} token - JWT token to validate
* @param {object} options - Validation options
* @returns {Promise<object>} Validated token claims
*/
async function validateAadToken(token, options = {}) {
const { isAppOnly = false, tenantId = null, audience = null } = options;
// Decode token to get header and tenant
const decoded = jwt.decode(token, { complete: true });
if (!decoded) {
throw new Error('Invalid token format');
}
const { header, payload } = decoded;
const tokenTenantId = payload.tid;
// Get signing key from Azure AD
const client = jwksClient({
jwksUri: `https://login.microsoftonline.com/${tokenTenantId}/discovery/v2.0/keys`,
cache: true,
cacheMaxAge: 86400000 // 24 hours
});
const signingKey = await new Promise((resolve, reject) => {
client.getSigningKey(header.kid, (err, key) => {
if (err) reject(err);
else resolve(key.getPublicKey());
});
});
// Verify token signature and claims
const verifyOptions = {
algorithms: ['RS256'],
audience: audience,
clockTolerance: 60 // 1 minute clock skew
};
const verified = jwt.verify(token, signingKey, verifyOptions);
// Validate app-only vs delegated token
if (isAppOnly) {
if (verified.idtyp !== 'app') {
throw new Error('Expected app-only token');
}
if (verified.scp) {
throw new Error('App-only token should not have scp claim');
}
} else {
if (verified.idtyp) {
throw new Error('Expected delegated token');
}
if (!verified.scp || !verified.scp.includes('FabricWorkloadControl')) {
throw new Error('Missing required FabricWorkloadControl scope');
}
}
// Validate tenant if required
if (tenantId && verified.tid !== tenantId) {
throw new Error(`Token tenant mismatch: expected ${tenantId}, got ${verified.tid}`);
}
return verified;
}
認證中介軟體
實作中介軟體來驗證來自 Fabric 的輸入請求。
完整認證流程
/**
* Authentication middleware that validates control plane calls from Fabric
* Handles both user-delegated (with subjectToken) and app-only (without subjectToken) scenarios
* @param {object} req - Express request object
* @param {object} res - Express response object
* @param {object} options - Authentication options
* @param {boolean} options.requireSubjectToken - Whether subject token is required (default: false)
* @returns {Promise<boolean>} True if authenticated successfully
*/
async function authenticateControlPlaneCall(req, res, options = {}) {
const { requireSubjectToken = false } = options;
try {
// Extract and parse authorization header
const authHeader = req.headers['authorization'];
if (!authHeader) {
return res.status(401).json({ error: 'Missing Authorization header' });
}
const tokens = parseSubjectAndAppToken(authHeader);
if (!tokens || !tokens.appToken) {
return res.status(401).json({ error: 'Invalid Authorization header format' });
}
// Get tenant ID from header
const tenantId = req.headers['ms-client-tenant-id'];
if (!tenantId) {
return res.status(400).json({ error: 'Missing ms-client-tenant-id header' });
}
// Get configuration
const publisherTenantId = process.env.TENANT_ID;
const audience = process.env.BACKEND_AUDIENCE;
const fabricBackendAppId = '00000009-0000-0000-c000-000000000000';
// Validate app token (from Fabric)
const appTokenClaims = await validateAadToken(tokens.appToken, {
isAppOnly: true,
audience: audience
});
// Verify app token is from Fabric
const appTokenAppId = appTokenClaims.appid || appTokenClaims.azp;
if (appTokenAppId !== fabricBackendAppId) {
return res.status(401).json({ error: 'App token not from Fabric' });
}
// Verify app token is in publisher's tenant
if (publisherTenantId && appTokenClaims.tid !== publisherTenantId) {
return res.status(401).json({ error: 'App token tenant mismatch' });
}
// Validate subject token if present
let subjectTokenClaims = null;
if (tokens.subjectToken) {
subjectTokenClaims = await validateAadToken(tokens.subjectToken, {
isAppOnly: false,
audience: audience,
tenantId: tenantId
});
// Verify subject token has same appid as app token
const subjectAppId = subjectTokenClaims.appid || subjectTokenClaims.azp;
if (subjectAppId !== appTokenAppId) {
return res.status(401).json({ error: 'Token appid mismatch' });
}
} else if (requireSubjectToken) {
// If subject token is required but missing, reject the request
return res.status(401).json({
error: 'Subject token required for this operation'
});
}
// Store authentication context in request
req.authContext = {
subjectToken: tokens.subjectToken,
appToken: tokens.appToken,
tenantId: tenantId,
hasSubjectContext: !!tokens.subjectToken,
appTokenClaims: appTokenClaims,
subjectTokenClaims: subjectTokenClaims,
userId: subjectTokenClaims?.oid || subjectTokenClaims?.sub,
userName: subjectTokenClaims?.name || subjectTokenClaims?.upn
};
return true; // Authentication successful
} catch (error) {
console.error('Authentication failed:', error.message);
res.status(401).json({ error: 'Authentication failed' });
return false;
}
}
使用中介軟體
app.post('/api/jobs/execute', async (req, res) => {
// Authenticate the request (subjectToken is optional)
const authenticated = await authenticateControlPlaneCall(req, res);
if (!authenticated) {
return; // Response already sent by middleware
}
// Access authentication context
const { hasSubjectContext, userId, userName, tenantId, subjectToken } = req.authContext;
if (hasSubjectContext) {
console.log(`Executing job for user: ${userName} (${userId})`);
} else {
console.log('Executing job in app-only context (no user)');
}
// Execute job logic...
});
// Example: Require user context for specific operations
app.post('/api/lifecycle/create', async (req, res) => {
// For create operations, we might require user context
const authenticated = await authenticateControlPlaneCall(req, res, {
requireSubjectToken: true
});
if (!authenticated) {
return; // Response already sent by middleware
}
// User context is guaranteed to be present here
const { userId, userName } = req.authContext;
console.log(`Creating item for user: ${userName}`);
// Handle creation...
});
// Example: Allow app-only context for delete operations
app.post('/api/lifecycle/delete', async (req, res) => {
// Delete operations might not have user context
const authenticated = await authenticateControlPlaneCall(req, res, {
requireSubjectToken: false // Default, but shown for clarity
});
if (!authenticated) {
return;
}
const { hasSubjectContext, userName } = req.authContext;
if (hasSubjectContext) {
console.log(`Deleting item for user: ${userName}`);
} else {
console.log('Deleting item (system operation)');
}
// Handle deletion...
});
代幣交換 - 代表(OBO)流程
若要呼叫 Fabric API 或從遠端端點存取 OneLake,您需要使用 OAuth 2.0 On-Behalf-Of 流程,將使用者的 subjectToken 換成資源專屬的 tokens。
代幣交換服務
const https = require('https');
const { URL } = require('url');
const AAD_LOGIN_URL = 'https://login.microsoftonline.com';
const ONELAKE_SCOPE = 'https://storage.azure.com/.default';
const FABRIC_SCOPE = 'https://analysis.windows.net/powerbi/api/.default';
/**
* Get token for any scope using OBO flow
* @param {string} userToken - User's access token (subjectToken)
* @param {string} tenantId - User's tenant ID
* @param {string} scope - Target resource scope
* @returns {Promise<string>} Access token for the requested scope
* @throws {Error} Throws consent-related errors (AADSTS65001, AADSTS65005) that should be propagated to UX
*/
async function getTokenForScope(userToken, tenantId, scope) {
const clientId = process.env.BACKEND_APPID;
const clientSecret = process.env.BACKEND_CLIENT_SECRET;
if (!clientId || !clientSecret) {
throw new Error('BACKEND_APPID and BACKEND_CLIENT_SECRET required');
}
const tokenEndpoint = `${AAD_LOGIN_URL}/${tenantId}/oauth2/v2.0/token`;
const requestBody = new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
client_id: clientId,
client_secret: clientSecret,
assertion: userToken,
scope: scope,
requested_token_use: 'on_behalf_of'
}).toString();
const response = await makeTokenRequest(tokenEndpoint, requestBody);
if (!response.access_token) {
throw new Error('Token exchange failed: missing access_token');
}
return response.access_token;
}
/**
* Get OneLake access token
* @param {string} userToken - User's access token from authContext
* @param {string} tenantId - User's tenant ID
* @returns {Promise<string>} OneLake access token
*/
async function getOneLakeToken(userToken, tenantId) {
return getTokenForScope(userToken, tenantId, ONELAKE_SCOPE);
}
/**
* Get Fabric OBO token for calling Fabric APIs
* @param {string} userToken - User's access token
* @param {string} tenantId - User's tenant ID
* @returns {Promise<string>} Fabric OBO token
*/
async function getFabricOboToken(userToken, tenantId) {
return getTokenForScope(userToken, tenantId, FABRIC_SCOPE);
}
/**
* Make HTTPS request to token endpoint
*/
function makeTokenRequest(url, body) {
return new Promise((resolve, reject) => {
const parsedUrl = new URL(url);
const options = {
hostname: parsedUrl.hostname,
port: 443,
path: parsedUrl.pathname,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body)
}
};
const req = https.request(options, (res) => {
let responseBody = '';
res.on('data', (chunk) => { responseBody += chunk; });
res.on('end', () => {
const parsed = JSON.parse(responseBody);
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(parsed);
} else {
const error = parsed.error_description || parsed.error || `HTTP ${res.statusCode}`;
reject(new Error(error));
}
});
});
req.on('error', reject);
req.write(body);
req.end();
});
}
使用代幣交換
// In your job or lifecycle notification handler
async function handleJobExecution(req, res) {
const authenticated = await authenticateControlPlaneCall(req, res);
if (!authenticated) return;
const { hasSubjectContext, subjectToken, tenantId } = req.authContext;
try {
// Only exchange token if user context is available
if (hasSubjectContext) {
// Get OneLake token to access item data on behalf of the user
const oneLakeToken = await getOneLakeToken(subjectToken, tenantId);
// Use OneLake token to read/write data
const data = await readFromOneLake(oneLakeToken, workspaceId, itemId);
// Process data...
} else {
// Handle app-only scenario
// You may need to use different authentication or skip user-specific operations
console.log('Processing job without user context');
// Use workspace or item-level access instead
}
res.status(200).json({ status: 'completed' });
} catch (error) {
console.error('Job execution failed:', error);
res.status(500).json({ error: 'Job execution failed' });
}
}
呼叫 Fabric API
要呼叫 Fabric 工作負載控制 API,你需要建構一個包含 OBO 和 S2S 令牌的 SubjectAndAppToken。
服務對服務(S2S)令牌
除了 OBO 代幣外,AppToken 部分還需要一個僅限 App 的 S2S 代幣。
/**
* Get S2S (Service-to-Service) token using client credentials flow
* @param {string} tenantId - Publisher's tenant ID
* @param {string} scope - Target resource scope
* @returns {Promise<string>} S2S access token
*/
async function getS2STokenForScope(tenantId, scope) {
const clientId = process.env.BACKEND_APPID;
const clientSecret = process.env.BACKEND_CLIENT_SECRET;
if (!clientId || !clientSecret) {
throw new Error('BACKEND_APPID and BACKEND_CLIENT_SECRET required');
}
const tokenEndpoint = `${AAD_LOGIN_URL}/${tenantId}/oauth2/v2.0/token`;
const requestBody = new URLSearchParams({
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
scope: scope
}).toString();
const response = await makeTokenRequest(tokenEndpoint, requestBody);
if (!response.access_token) {
throw new Error('S2S token acquisition failed');
}
return response.access_token;
}
/**
* Get Fabric S2S token
* @param {string} publisherTenantId - Publisher's tenant ID
* @returns {Promise<string>} Fabric S2S access token
*/
async function getFabricS2SToken(publisherTenantId) {
return getS2STokenForScope(publisherTenantId, FABRIC_SCOPE);
}
為 Fabric API 建構複合令牌
/**
* Build composite token for Fabric API calls
* @param {object} authContext - Authentication context
* @returns {Promise<string>} SubjectAndAppToken formatted header value
*/
async function buildCompositeToken(authContext) {
const { subjectToken, tenantId } = authContext;
const publisherTenantId = process.env.TENANT_ID;
if (!subjectToken) {
throw new Error('Subject token is required');
}
// Exchange user's subject token for Fabric OBO token
const fabricOboToken = await getFabricOboToken(subjectToken, tenantId);
// Acquire S2S token using publisher tenant
const fabricS2SToken = await getFabricS2SToken(publisherTenantId);
// Combine into SubjectAndAppToken format
return `SubjectAndAppToken1.0 subjectToken="${fabricOboToken}", appToken="${fabricS2SToken}"`;
}
呼叫 Fabric API 範例
const axios = require('axios');
/**
* Call Fabric workload control API
*/
async function callFabricApi(authContext, workspaceId, itemId) {
// Build composite token
const authHeader = await buildCompositeToken(authContext);
// Call Fabric API
const response = await axios.get(
`https://api.fabric.microsoft.com/v1/workspaces/${workspaceId}/items/${itemId}`,
{
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json'
}
}
);
return response.data;
}
完整範例:使用認證的工作執行
以下是一個帶有認證的工作執行端點完整範例:
const express = require('express');
const app = express();
app.post('/api/jobs/:jobType/instances/:instanceId', async (req, res) => {
// Authenticate the request from Fabric
const authenticated = await authenticateControlPlaneCall(req, res);
if (!authenticated) {
return; // Response already sent
}
const { jobType, instanceId } = req.params;
const { workspaceId, itemId } = req.body;
const { subjectToken, tenantId, userId } = req.authContext;
console.log(`Starting job ${jobType} for user ${userId}`);
try {
// Get OneLake token to access item data
const oneLakeToken = await getOneLakeToken(subjectToken, tenantId);
// Read data from OneLake
const itemData = await readItemData(oneLakeToken, workspaceId, itemId);
// Process the job
const result = await processJob(jobType, itemData);
// Write results back to OneLake
await writeResults(oneLakeToken, workspaceId, itemId, result);
// Return success
res.status(202).json({
status: 'InProgress',
instanceId: instanceId,
message: 'Job started successfully'
});
} catch (error) {
console.error(`Job ${instanceId} failed:`, error);
res.status(500).json({
status: 'Failed',
instanceId: instanceId,
error: error.message
});
}
});
長時間執行操作
對於長期執行的作業如工作,代幣可能在完成前即過期。 建立令牌更新邏輯:
// Store refresh tokens securely
const tokenCache = new Map();
/**
* Get cached token or acquire new one
*/
async function getOrRefreshToken(userToken, tenantId, scope, cacheKey) {
const cached = tokenCache.get(cacheKey);
// Check if cached token is still valid (with 5 min buffer)
if (cached && cached.expiresAt > Date.now() + 300000) {
return cached.token;
}
// Acquire new token
const response = await getTokenForScopeWithRefresh(userToken, tenantId, scope);
// Cache the token
tokenCache.set(cacheKey, {
token: response.access_token,
expiresAt: Date.now() + (response.expires_in * 1000)
});
return response.access_token;
}
欲了解更多關於處理長期運行的 OBO 程序的資訊,請參閱 「長期運行的 OBO 程序」。
安全性最佳做法
令牌儲存
- 千萬不要記錄完整的標記——只記錄最後 4 個字元以便除錯
- 將代幣安全地儲存在記憶體中
- 使用後清除記憶中的標記
- 不要將標記持久化到磁碟或資料庫
令牌驗證
- 請務必以 SubjectAndAppToken 格式驗證 appToken
- 只有在 subjectToken 存在時才驗證
- 在 Azure AD 金鑰中驗證令牌的簽名
- 檢查令牌到期時間及非提前時間
- 驗證發行人、受眾及承租人主張
- 確認必要的申請(如 SCP、idtype 等)
處理缺少使用者上下文
- 設計您的遠端端點,以同時應對使用者委派與僅限應用程式的情境。
- 在存取使用者專屬屬性前,請先在 authContext 中確認
hasSubjectContext - 對於需要使用者上下文的操作,請在中介軟體中設定
requireSubjectToken: true選項 - 對於刪除操作或系統操作,允許缺少主體令牌
- 記錄哪些操作支援僅應用程式上下文,哪些需要使用者上下文
環境設定
// Required environment variables
const requiredEnvVars = [
'BACKEND_APPID', // Your workload's app registration ID
'BACKEND_CLIENT_SECRET', // Your app's client secret
'TENANT_ID', // Your publisher tenant ID
'BACKEND_AUDIENCE' // Expected token audience
];
// Validate on startup
requiredEnvVars.forEach(varName => {
if (!process.env[varName]) {
throw new Error(`Missing required environment variable: ${varName}`);
}
});
錯誤處理與同意傳播
當代幣交換因缺乏同意或範圍而失敗時,你的後端應該將這些錯誤傳播到前端 UX 以提示使用者同意。 常見的同意相關錯誤包括:
- AADSTS65001 - 使用者或管理員尚未同意使用該應用程式
- AADSTS65005 - 申請要求未獲同意的特定範圍
/**
* Handle token exchange with consent error propagation
* Consent errors should be returned to the frontend to trigger consent flow
*/
async function handleTokenExchangeWithConsent(req, res) {
const { subjectToken, tenantId } = req.authContext;
const clientId = process.env.BACKEND_APPID;
try {
const token = await getTokenForScope(subjectToken, tenantId, ONELAKE_SCOPE);
// Use token for OneLake operations...
} catch (error) {
// Check for consent-related errors
if (error.message.includes('AADSTS65001') || error.message.includes('AADSTS65005')) {
// Extract scope from error if available
const requiredScope = extractScopeFromError(error.message) || 'https://storage.azure.com/.default';
// Build consent URL for the frontend to redirect the user
const consentUrl = buildConsentUrl({
clientId: clientId,
tenantId: tenantId,
scope: requiredScope,
redirectUri: process.env.FRONTEND_URL || 'https://your-frontend.azurewebsites.net'
});
// Return consent required response
return res.status(403).json({
error: 'ConsentRequired',
errorCode: error.message.includes('AADSTS65001') ? 'AADSTS65001' : 'AADSTS65005',
message: 'User consent is required to access this resource',
consentUrl: consentUrl,
requiredScope: requiredScope
});
}
// Other errors should be handled normally
throw error;
}
}
/**
* Build consent URL for user authorization
* @param {object} options - Consent URL options
* @returns {string} Formatted consent URL
*/
function buildConsentUrl(options) {
const { clientId, tenantId, scope, redirectUri } = options;
const params = new URLSearchParams({
client_id: clientId,
response_type: 'code',
redirect_uri: redirectUri,
response_mode: 'query',
scope: scope,
state: 'consent_required' // Your frontend can use this to handle the redirect
});
return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize?${params.toString()}`;
}
/**
* Extract scope from error message
*/
function extractScopeFromError(errorMessage) {
// Azure AD error messages often include the missing scope
const scopeMatch = errorMessage.match(/scope[s]?[:\s]+([^\s,]+)/);
return scopeMatch ? scopeMatch[1] : null;
}
前端同意處理
當你的前端收到 ConsentRequired 錯誤時,應該會將使用者重新導向到同意網址:
// Frontend code to handle consent errors
async function callBackendApi(endpoint, data) {
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (response.status === 403) {
const error = await response.json();
if (error.error === 'ConsentRequired' && error.consentUrl) {
// Redirect user to consent page
window.location.href = error.consentUrl;
return;
}
}
return await response.json();
} catch (error) {
console.error('API call failed:', error);
throw error;
}
}
備註
Fabric 工作負載開發範例包含了同意錯誤處理及前端 UX 傳播的完整範例。 請參閱範例中的認證中介軟體與前端錯誤處理,以了解用於生產環境的實作。
其他錯誤情境
// Handle various token exchange errors
try {
const token = await getTokenForScope(subjectToken, tenantId, scope);
} catch (error) {
const errorMessage = error.message;
if (errorMessage.includes('AADSTS65001') || errorMessage.includes('AADSTS65005')) {
// Consent required - propagate to frontend
return propagateConsentError(res, error, tenantId);
} else if (errorMessage.includes('AADSTS50013')) {
// Invalid assertion - token may be expired
return res.status(401).json({
error: 'InvalidToken',
message: 'The provided token is invalid or expired'
});
} else if (errorMessage.includes('AADSTS700016')) {
// Application not found in tenant
return res.status(400).json({
error: 'ApplicationNotFound',
message: 'Application is not configured in this tenant'
});
}
// Unknown error
throw error;
}
Troubleshooting
常見的認證問題
錯誤:「無效的標記格式」
- 請確認授權標頭以
SubjectAndAppToken1.0開頭。 - 檢查 subjectToken 和 appToken 是否同時存在
- 確保標籤在標頭中被正確引用
錯誤:「憑證驗證失敗」
- 確認BACKEND_APPID與你的應用程式註冊相符
- 檢查BACKEND_AUDIENCE設定是否正確
- 確保代幣沒有過期
- 確認發行商是否符合你的 Azure AD 租戶
錯誤:「代幣交換失敗:AADSTS65001」
- 申請範圍需用戶同意
- 確保你的應用程式註冊擁有必要的 API 權限
- 如有需要,請確認管理員同意已被核發
錯誤:「應用程式權杖並非來自 Fabric」
- 確認 appToken 的
appid申訴是否與 Fabric 的應用程式 ID 相符 - 確認你是在正確的環境(開發/生產環境)測試。