教學:以使用者身份從安全 JavaScript 應用程式存取 Microsoft Graph

了解如何從運行於 Azure App Service 上的網頁應用程式存取 Microsoft Graph。

圖示,顯示存取 Microsoft Graph.

你想從你的網頁應用程式新增對 Microsoft Graph 的存取權限,並以登入使用者的身份執行某些操作。 本節說明如何授予網頁應用程式授權權限,並從 Microsoft Entra ID 取得已登入使用者的個人資料資訊。

在本教學課程中,您會了解如何:

  • 將委派的權限授與 Web 應用程式。
  • 從 Web 應用程式為已登入的使用者呼叫 Microsoft Graph

如果你沒有Azure帳號,請在開始前先建立一個free帳號

必要條件

授予前端存取權以呼叫 Microsoft Graph

在你啟用網頁應用程式的認證與授權後,網頁應用程式會註冊在 Microsoft 身份平台,並由 Microsoft Entra 應用程式支援。 在此步驟中,你給予網頁應用程式存取 Microsoft Graph 的權限給使用者。

Note

嚴格來說,您會授與 Web 應用程式的 Microsoft Entra 應用程式權限,以代表使用者存取 Microsoft Graph Microsoft Entra 應用程式。

  1. Microsoft Entra admin center中,選擇Entra ID

  2. 選擇 應用程式註冊>擁有的應用程式>查看此目錄中的所有應用程式。 選取您的 Web 應用程式名稱,然後選取 [API 權限]

  3. 選擇 新增權限,然後選擇 Microsoft APIS,再選 Microsoft Graph

  4. 選取 [委派的權限],然後從清單中選取 [User.Read]。 選取新增權限

設定 App Service 以便傳回可用的存取權杖

網頁應用程式現在擁有登入使用者存取 Microsoft Graph 所需的權限。 在本節中,你要設定 App Service 認證與授權,以獲得可用的存取權杖來存取 Microsoft Graph。 此步驟需新增 User.Read 下游服務(Microsoft Graph)的範圍: https://graph.microsoft.com/User.Read

重要

如果你沒有設定 App Service 回傳可用的存取權杖,當你在程式碼中呼叫 Microsoft Graph API 時,會收到 CompactToken parsing failed with error code: 80049217 錯誤。

請到 Azure資源瀏覽器,利用資源樹找到你的網頁應用程式。 資源網址應該類似於 https://management.azure.com/subscriptions/subscriptionId/resourceGroups/SecureWebApp/providers/Microsoft.Web/sites/SecureWebApp20200915115914

Azure 資源總管現已開啟,且您的 Web 應用程式已在資源樹狀結構中選取。

  1. 在頁面頂端,選擇 Edit 以啟用編輯您的Azure資源。

  2. 在左側瀏覽器中,向下切入至 [config]>[authsettingsV2]

  3. 在 [authsettingsV2] 檢視中,選取 [編輯]

  4. 找到 identityProviders> 的登入區塊,並新增以下 loginParameters 設定: "loginParameters":[ "response_type=code id_token","scope=openid offline_access profile https://graph.microsoft.com/User.Read" ]

    "identityProviders": {
        "azureActiveDirectory": {
          "enabled": true,
          "login": {
            "loginParameters":[
              "response_type=code id_token",
              "scope=openid offline_access profile https://graph.microsoft.com/User.Read"
            ]
          }
        }
      }
    },
    
  5. 選取 [PUT] 來儲存您的設定。

此設定可能需要幾分鐘才會生效。 你的網頁應用程式現在已經設定為能用正確的存取權杖存取 Microsoft Graph。 如果沒有,Microsoft Graph 會回傳錯誤,說 compact token 格式錯誤。

從 Node.js 調用 Microsoft Graph

你的網頁應用程式現在擁有所需的權限。 它也會將 Microsoft Graph 的客戶端 ID 加入登入參數。

安裝用戶端程式庫套件

用 npm 安裝 @azure/identity 以及 @microsoft/microsoft-graph-client 套件。

npm install @microsoft/microsoft-graph-client

設定驗證資訊

建立物件來保存驗證設定 (英文):

// partial code in app.js
const appSettings = {
    appCredentials: {
        clientId: process.env.WEBSITE_AUTH_CLIENT_ID, // Enter the client Id here,
        tenantId: "common", // Enter the tenant info here,
        clientSecret: process.env.MICROSOFT_PROVIDER_AUTHENTICATION_SECRET // Enter the client secret here,
    },
    authRoutes: {
        redirect: "/.auth/login/aad/callback", // Enter the redirect URI here
        error: "/error", // enter the relative path to error handling route
        unauthorized: "/unauthorized" // enter the relative path to unauthorized route
    },
    protectedResources: {
        graphAPI: {
            endpoint: "https://graph.microsoft.com/v1.0/me", // resource endpoint
            scopes: ["User.Read"] // resource scopes
        },
    },
}

代表使用者致電 Microsoft Graph

以下程式碼說明如何以應用程式呼叫 Microsoft Graph 控制器並取得使用者資訊。

// controllers/graphController.js

// get the name of the app service instance from environment variables
const appServiceName = process.env.WEBSITE_SITE_NAME;

const graphHelper = require('../utils/graphHelper');

exports.getProfilePage = async(req, res, next) => {

    try {
        // get user's access token scoped to Microsoft Graph from session
        // use token to create Graph client
        const graphClient = graphHelper.getAuthenticatedClient(req.session.protectedResources["graphAPI"].accessToken);

        // return user's profile
        const profile = await graphClient
            .api('/me')
            .get();

        res.render('profile', { isAuthenticated: req.session.isAuthenticated, profile: profile, appServiceName: appServiceName });   
    } catch (error) {
        next(error);
    }
}

前述程式碼依賴以下 getAuthenticatedClient 函式來回傳 Microsoft Graph 用戶端。

// utils/graphHelper.js

const graph = require('@microsoft/microsoft-graph-client');

getAuthenticatedClient = (accessToken) => {
    // Initialize Graph client
    const client = graph.Client.init({
        // Use the provided access token to authenticate requests
        authProvider: (done) => {
            done(null, accessToken);
        }
    });

    return client;
}

清除資源

如果您已完成此多部分教學課程中的所有步驟,就會在資源群組中建立應用程式服務、應用程式服務主控方案和儲存體帳戶。 你也在 Microsoft Entra ID 建立了應用程式註冊。 如果你選擇了外部設定,可能已經建立了新的外部租戶。 當不再需要這些資源和應用程式註冊時,請加以刪除,才不會繼續累積費用。

在本教學課程中,您會了解如何:

  • 刪除跟著教學建立的 Azure 資源。

刪除資源群組

  1. Azure 入口網站的 Azure 入口網站選單中,選擇 資源群組

  2. 選擇包含您的 App Service 及 App Service 計畫的資源群組。

  3. 選取 [刪除資源群組] 來刪除群組及所有資源。

    顯示刪除資源群組的螢幕擷取畫面。

這個動作可能需要幾分鐘。

刪除應用程式註冊

  1. Microsoft Entra admin center中,選擇App registrations。 然後選取您建立的應用程式。

    截圖顯示選擇應用程式註冊。

  2. 在應用程式註冊概觀中,選取 [刪除]

    截圖顯示刪除應用程式註冊。

刪除外部租戶

如果您已建立新的外部租戶,則可以刪除

  1. Microsoft Entra 管理中心,瀏覽至 Entra ID>Overview>管理租戶

  2. 選取您要刪除的租用戶,然後選取 [刪除]

    您可能需要先完成必要的動作,才能刪除租用戶。 例如,您可能需要刪除租戶中的所有使用者流程和應用程式註冊。

  3. 如果您已準備好刪除租用戶,請選取 [刪除]

下一步

在本教學課程中,您已了解如何:

  • 將委派的權限授與 Web 應用程式。
  • 從 Web 應用程式為已登入的使用者呼叫 Microsoft Graph