教學課程:在 Node.js 主控台精靈應用程式中呼叫 Microsoft Graph API
在本教學課程中,您會建置主控台精靈應用程式,以使用自己的身分識別來呼叫 Microsoft Graph API。 您建置的精靈應用程式會使用適用于 Node.js 的 Microsoft 驗證程式庫 (MSAL)。
請遵循本教學課程中的步驟來:
- 在Azure 入口網站中註冊應用程式
- 建立 Node.js 主控台精靈應用程式專案
- 將驗證邏輯新增至您的應用程式
- 新增應用程式註冊詳細資料
- 新增方法以呼叫 Web API
- 測試應用程式
必要條件
- Node.js
- Visual Studio Code 或其他程式碼編輯器
註冊應用程式
首先,完成向 Microsoft 身分識別平臺 註冊應用程式中的 步驟,以註冊您的應用程式。
針對您的應用程式註冊使用下列設定:
- 名稱:
NodeDaemonApp
(建議) - 支援的帳戶類型: 僅限此組織目錄中的帳戶
- API 許可權: Microsoft API > Microsoft Graph > 應用程式許可權>
User.Read.All
- 用戶端密碼:
*********
(記錄此值以供後續步驟使用 - 只會顯示一次)
建立專案
從建立此 Node.js 教學課程專案的目錄開始。 例如, NodeDaemonApp 。
在您的終端機中,變更為您建立的目錄(專案根目錄),然後執行下列命令:
npm init -y npm install --save dotenv yargs axios @azure/msal-node
接下來,編輯 專案根目錄中的 package.json 檔案,並在 的值
main
前面加上bin/
,如下所示:"main": "bin/index.js",
現在建立 bin 目錄,並在 bin 內 ,將下列程式碼新增至名為 index.js 的新檔案:
#!/usr/bin/env node // read in env settings require('dotenv').config(); const yargs = require('yargs'); const fetch = require('./fetch'); const auth = require('./auth'); const options = yargs .usage('Usage: --op <operation_name>') .option('op', { alias: 'operation', describe: 'operation name', type: 'string', demandOption: true }) .argv; async function main() { console.log(`You have selected: ${options.op}`); switch (yargs.argv['op']) { case 'getUsers': try { // here we get an access token const authResponse = await auth.getToken(auth.tokenRequest); // call the web API with the access token const users = await fetch.callApi(auth.apiConfig.uri, authResponse.accessToken); // display result console.log(users); } catch (error) { console.log(error); } break; default: console.log('Select a Graph operation first'); break; } }; main();
您剛才建立的 index.js 檔案會參考接下來建立的另外兩個節點模組:
- auth.js - 使用 MSAL 節點從Microsoft 身分識別平臺取得存取權杖。
- fetch.js - 在對 API 的 HTTP 要求中包含存取權杖(以 auth.js 取得 )從 Microsoft Graph API 要求資料。
在本教學課程結束時,專案的檔案和目錄結構看起來應該如下所示:
NodeDaemonApp/
├── bin
│ ├── auth.js
│ ├── fetch.js
│ ├── index.js
├── package.json
└── .env
新增驗證邏輯
在 bin 目錄中,將下列程式碼新增至名為 auth.js 的新檔案。 auth.js 中的 程式碼會從Microsoft 身分識別平臺取得存取權杖,以包含在 Microsoft Graph API 要求中。
const msal = require('@azure/msal-node');
/**
* Configuration object to be passed to MSAL instance on creation.
* For a full list of MSAL Node configuration parameters, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/configuration.md
*/
const msalConfig = {
auth: {
clientId: process.env.CLIENT_ID,
authority: process.env.AAD_ENDPOINT + '/' + process.env.TENANT_ID,
clientSecret: process.env.CLIENT_SECRET,
}
};
/**
* With client credentials flows permissions need to be granted in the portal by a tenant administrator.
* The scope is always in the format '<resource>/.default'. For more, visit:
* https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
*/
const tokenRequest = {
scopes: [process.env.GRAPH_ENDPOINT + '/.default'],
};
const apiConfig = {
uri: process.env.GRAPH_ENDPOINT + '/v1.0/users',
};
/**
* Initialize a confidential client application. For more info, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/initialize-confidential-client-application.md
*/
const cca = new msal.ConfidentialClientApplication(msalConfig);
/**
* Acquires token with client credentials.
* @param {object} tokenRequest
*/
async function getToken(tokenRequest) {
return await cca.acquireTokenByClientCredential(tokenRequest);
}
module.exports = {
apiConfig: apiConfig,
tokenRequest: tokenRequest,
getToken: getToken
};
在上述程式碼片段中,我們會先建立組態物件 ( msalConfig ),並傳遞它以初始化 MSAL ConfidentialClientApplication 。 然後,我們會建立方法,以透過 用戶端認證 取得權杖,最後公開 此模組以供 main.js 存取。 本課程模組中的組態參數會從環境檔案中繪製,我們將在下一個步驟中建立。
新增應用程式註冊詳細資料
建立環境檔案來儲存取得權杖時將使用的應用程式註冊詳細資料。 若要這樣做,請在範例的根資料夾內建立名為 .env 的檔案( NodeDaemonApp ),並新增下列程式碼:
# Credentials
TENANT_ID=Enter_the_Tenant_Id_Here
CLIENT_ID=Enter_the_Application_Id_Here
CLIENT_SECRET=Enter_the_Client_Secret_Here
# Endpoints
AAD_ENDPOINT=Enter_the_Cloud_Instance_Id_Here/
GRAPH_ENDPOINT=Enter_the_Graph_Endpoint_Here/
以您從 Azure 應用程式註冊入口網站取得的值填入這些詳細資料:
Enter_the_Tenant_Id_here
應該是下列其中一項:- 如果您的應用程式支援 此組織目錄中 的帳戶,請將此值取代為 租使用者識別碼 或 租使用者名稱 。 例如:
contoso.microsoft.com
。 - 如果您的應用程式支援 任何組織目錄中 的帳戶,請將此值取代為
organizations
。 - 如果您的應用程式支援 任何組織目錄和個人 Microsoft 帳戶中的帳戶 ,請將此值取代為
common
。 - 若要限制僅 對個人 Microsoft 帳戶的支援 ,請將此值取代為
consumers
。
- 如果您的應用程式支援 此組織目錄中 的帳戶,請將此值取代為 租使用者識別碼 或 租使用者名稱 。 例如:
Enter_the_Application_Id_Here
:您註冊之應用程式的應用程式(用戶端)識別碼 。Enter_the_Cloud_Instance_Id_Here
:註冊應用程式的 Azure 雲端實例。- 針對主要(或 全域 )Azure 雲端,輸入
https://login.microsoftonline.com
。 - 針對 國家 雲端(例如中國),您可以在國家雲端 中找到 適當的值。
- 針對主要(或 全域 )Azure 雲端,輸入
Enter_the_Graph_Endpoint_Here
是應用程式應該與其通訊的 Microsoft Graph API 實例。- 針對全域 Microsoft Graph API 端點,請將此字串的兩個實例取代為
https://graph.microsoft.com
。 - 如需國家雲端部署中的 端點,請參閱 Microsoft Graph 檔中的國家 雲端部署 。
- 針對全域 Microsoft Graph API 端點,請將此字串的兩個實例取代為
新增方法以呼叫 Web API
在 bin 資料夾中,建立另一個名為 fetch.js 的檔案,並新增下列程式碼以對 Microsoft Graph API 進行 REST 呼叫:
const axios = require('axios');
/**
* Calls the endpoint with authorization bearer token.
* @param {string} endpoint
* @param {string} accessToken
*/
async function callApi(endpoint, accessToken) {
const options = {
headers: {
Authorization: `Bearer ${accessToken}`
}
};
console.log('request made to web API at: ' + new Date().toString());
try {
const response = await axios.get(endpoint, options);
return response.data;
} catch (error) {
console.log(error)
return error;
}
};
module.exports = {
callApi: callApi
};
在這裡,方法 callApi
可用來對需要存取權杖的受保護資源提出 HTTP GET
要求。 然後,要求會將內容傳回給呼叫端。 這個方法會在 HTTP 授權標頭 中新增取得的 權杖。 這裡的受保護資源是 Microsoft Graph API 使用者端點 ,其會顯示此應用程式註冊所在租使用者中的使用者。
測試應用程式
您已完成應用程式的建立,現在已準備好測試應用程式的功能。
從專案資料夾的根目錄中執行下列命令,以啟動 Node.js 主控台精靈應用程式:
node . --op getUsers
這應該會產生來自 Microsoft Graph API 的一些 JSON 回應,您應該會在主控台中看到使用者物件的陣列:
You have selected: getUsers
request made to web API at: Fri Jan 22 2021 09:31:52 GMT-0800 (Pacific Standard Time)
{
'@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users',
value: [
{
displayName: 'Adele Vance'
givenName: 'Adele',
jobTitle: 'Retail Manager',
mail: 'AdeleV@msaltestingjs.onmicrosoft.com',
mobilePhone: null,
officeLocation: '18/2111',
preferredLanguage: 'en-US',
surname: 'Vance',
userPrincipalName: 'AdeleV@msaltestingjs.onmicrosoft.com',
id: '00aa00aa-bb11-cc22-dd33-44ee44ee44ee'
}
]
}
應用程式的運作方式
此應用程式會使用 OAuth 2.0 用戶端認證授與 。 這類型的授與通常用於必須在背景中執行 (不需與使用者直接互動) 的伺服器對伺服器互動。 認證授與流程允許 Web 服務(機密用戶端)使用自己的認證,而不是模擬使用者,以在呼叫另一個 Web 服務時進行驗證。 此驗證模型所支援的應用程式類型通常是 精靈 或服務 帳戶 。
要求用戶端認證流程的範圍是資源的名稱, /.default
後面接著 。 此標記法會告知 Microsoft Entra ID 在應用程式註冊期間以靜態方式宣告的應用程式層級許可權。 此外,租使用者系統管理員 必須授 與這些 API 許可權。
下一步
如果您想要深入瞭解 Microsoft 身分識別平臺上的 Node.js 精靈應用程式開發,請參閱我們的多部分案例系列: