Share via


教學課程:以使用者身分,從安全的 JavaScrip 應用程式中存取 Microsoft Graph

了解如何從在 Azure App Service 上執行的 Web 應用程式存取 Microsoft Graph。

顯示存取 Microsoft Graph 的圖表。

您想要新增從 Web 應用程式存取 Microsoft Graph 的權限,並以登入的使用者身分執行某些動作。 本節說明如何將委派的權限授與 Web 應用程式,並從 Microsoft Entra ID 取得登入使用者的設定檔資訊。

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

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

如果您沒有 Azure 訂閱,請在開始之前,先建立 Azure 免費帳戶

必要條件

授與呼叫 Microsoft Graph 的前端存取權

您已在 Web 應用程式上啟用驗證和授權,Web 應用程式會向 Microsoft 身分識別平台註冊,並受到 Microsoft Entra 應用程式的支援。 在此步驟中,您會為使用者提供用來存取 Microsoft Graph 的 Web 應用程式權限。 (技術上,您會為 Web 應用程式的 Microsoft Entra 應用程式提供用來存取使用者 Microsoft Graph Microsoft Entra 應用程式的權限。)

  1. Microsoft Entra 系統管理中心中,選取 [應用程式]

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

  3. 選取 [新增權限],然後選取 Microsoft API 和 Microsoft Graph。

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

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

Web 應用程式現在具有必要權限,能夠以登入使用者的身分存取 Microsoft Graph。 在此步驟中,您會設定 App Service 驗證和授權,讓自己取得可用來存取 Microsoft Graph 的存取權杖。 針對此步驟,您必須為下游服務 (Microsoft Graph) 新增 User.Read 範圍:https://graph.microsoft.com/User.Read

重要

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

移至 Azure 資源總管並使用資源樹狀結構,找出您的 Web 應用程式。 此資源 URL 應類似於 https://resources.azure.com/subscriptions/subscriptionId/resourceGroups/SecureWebApp/providers/Microsoft.Web/sites/SecureWebApp20200915115914

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

  1. 在頁面頂端選取 [讀取/寫入],以啟用 Azure 資源的編輯。

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

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

  4. 尋找 identityProviders ->azureActiveDirectorylogin 區段,並新增下列 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] 來儲存您的設定。 此設定可能需要幾分鐘才會生效。 您的 Web 應用程式現在已設定為使用適當的存取權杖來存取 Microsoft Graph。 如果您沒有這麼做,Microsoft Graph 會傳回錯誤,指出精簡權杖的格式不正確。

從 Node.js 呼叫 Microsoft Graph

您的應用程式現已具有必要的權限,且會將 Microsoft Graph 的用戶端識別碼新增至登入參數。

若要查看應用程式範例中的此程式碼,請參閱:

安裝用戶端程式庫套件

使用 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;
}

清除資源

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

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

  • 刪除遵循教學課程時所建立的 Azure 資源。

刪除資源群組

在 Azure 入口網站 中,從入口網站功能表中選取 [資源群組],然後選取包含App Service和App Service 方案的資源群組。

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

顯示刪除資源群組的螢幕快照。

此命令可能需要幾分鐘的時間來執行。

刪除應用程式註冊

Microsoft Entra 系統管理中心中,選取 [應用程式]> [應用程式註冊]。 然後選取您建立的應用程式。 顯示選取應用程式註冊的螢幕快照。

在應用程式註冊概觀中,選取 [刪除]顯示刪除應用程式註冊的螢幕快照。

刪除外部租使用者

如果您已建立新的外部租使用者,則可以 將其刪除。 在 [Microsoft Entra 系統管理中心] 中,流覽至 [身分>識別概觀>管理租使用者]。

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

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

如果您已準備好刪除租使用者,請選取 [ 刪除]。

下一步

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

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