如何使用 Azure AD 存取 Intune 圖形 APIHow to use Azure AD to access the Intune Graph API

Microsoft Graph API 現在支援具有特定 API 和權限角色的 Microsoft Intune。The Microsoft Graph API now supports Microsoft Intune with specific APIs and permission roles. 圖形 API 使用 Azure Active Directory (Azure AD) 進行驗證和存取控制。The Graph API uses Azure Active Directory (Azure AD) for authentication and access control.
對於 Intune 圖形 API 的存取需要:Access to the Intune Graph API requires:

  • 具有以下項目的應用程式識別碼:An application ID with:

    • 呼叫 Azure AD 和圖形 API 的權限。Permission to call Azure AD and Graph APIs.
    • 與特定應用程式工作相關的權限範圍。Permission scopes relevant to the specific application tasks.
  • 具有以下項目的使用者認證:User credentials with:

    • 存取與應用程式相關之 Azure AD 租用戶的權限。Permission to access the Azure AD tenant associated with the application.
    • 支援應用程式權限範圍所需的角色權限。Role permissions required to support the application permission scopes.
  • 將權限授與應用程式以為其 Azure 租用戶執行應用程式工作的使用者。The end user to grant permission to the app to perform applications tasks for their Azure tenant.

這篇文章:This article:

  • 示範如何使用圖形 API 和相關權限角色的存取權註冊應用程式。Shows how to register an application with access to the Graph API and relevant permission roles.

  • 描述 Intune 圖形 API 權限角色。Describes the Intune Graph API permission roles.

  • 提供 C# 和 PowerShell 的 Intune 圖形 API 驗證範例。Provides Intune Graph API authentication examples for C# and PowerShell.

  • 描述如何支援多個租用戶Describes how to support multiple tenants

如需詳細資訊,請參閱:To learn more, see:

註冊應用程式以使用圖形 APIRegister apps to use Graph API

若要註冊應用程式以使用圖形 API:To register an app to use Graph API:

  1. 使用系統管理認證登入 Azure 入口網站Sign into the Azure portal using administrative credentials.

    您可以視需要使用以下項目:As appropriate, you may use:

    • 租用戶管理帳戶。The tenant admin account.
    • 已啟用 [使用者可以註冊應用程式] 設定的租用戶使用者帳戶。A tenant user account with the Users can register applications setting enabled.
  2. 從功能表中,選擇 [Azure Active Directory] > [應用程式註冊]。From the menu, choose Azure Active Directory > App Registrations.

    The App registrations menu command

  3. 選擇 [新增應用程式註冊] 來建立新應用程式,或選擇現有應用程式。Either choose New application registration to create a new application or choose an existing application. (如果您選擇現有應用程式,請略過下一步)。(If you choose an existing application, skip the next step.)

  4. 在 [建立] 刀鋒視窗中,指定下列各項︰On the Create blade, specify the following:

    1. 應用程式的 [名稱](於使用者登入時顯示)。A Name for the application (displayed when users sign in).

    2. [應用程式類型] 和 [重新導向 URI] 值。The Application type and Redirect URI values.

      這些值會因您的需求而不同。These vary according to your requirements. 例如,如果您使用 Azure AD 驗證程式庫 (ADAL),請將 [應用程式類型] 設定為 Native,並將 [重新導向 URI] 設定為 urn:ietf:wg:oauth:2.0:oobFor example, if you're using an Azure AD Authentication Library (ADAL), set Application Type to Native and Redirect URI to urn:ietf:wg:oauth:2.0:oob.

      New app properties and values

      若要深入了解,請參閱 Azure AD 的驗證案例To learn more, see Authentication Scenarios for Azure AD.

  5. 從應用程式刀鋒視窗中:From the application blade:

    1. 記下 [應用程式識別碼] 值。Note the Application ID value.

    2. 選擇 [設定] > [API 存取權] > [必要權限]。Choose Settings > API access > Required permissions.

    The Required permissions setting

  6. 從 [必要權限] 刀鋒視窗中,選擇 [新增] > [加入 API 存取權] > [選取 API]。From the Required Permissions blade, choose Add > Add API access > Select an API.

    The Microsoft Graph setting

  7. 從 [選取API] 刀鋒視窗中,選擇 [Microsoft Graph] > [選取]。From the Select an API blade, choose Microsoft Graph > Select. [啟用存取] 刀鋒視窗即會開啟,並列出可供您應用程式使用的權限範圍。The Enable access blade opens and lists permission scopes available to your application.

    Intune Graph API permission scopes

    在相關名稱左邊勾選核取記號,選擇應用程式所需的角色。Choose the roles required for your app by placing a checkmark to the left of the relevant names. 若要深入了解特定 Intune 權限範圍,請參閱 Intune 權限範圍To learn about specific Intune permission scopes, see Intune permission scopes. 若要深入了解其他圖形 API 權限範圍,請參閱 Microsoft Graph 權限參考 (英文)。To learn about other Graph API permission scopes, see Microsoft Graph permissions reference.

    為獲得最佳結果,請選擇實作應用程式所需的最少角色。For best results, choose the fewest roles needed to implement your application.

    完成後,請選擇 [選取] 和 [完成] 以儲存變更。When finished, choose Select and Done to save you changes.

此時,您也可以:At this point, you may also:

  • 選擇為要使用應用程式的所有租用戶帳戶授與權限,不需提供認證。Choose to grant permission for all tenant accounts to use the app without providing credentials.

    若要這樣做,請選擇 [授與權限] 並接受確認提示。To do so, choose Grant permissions and accept the confirmation prompt.

    當您第一次執行應用程式時,系統會提示您授與應用程式執行所選角色的權限。When you run the application for the first time, you're prompted to grant the app permission to perform the selected roles.

    The Grant permissions button

  • 讓您租用戶以外的使用者能夠使用應用程式Make the app available to users outside your tenant. (通常只有支援多個租用戶/組織的合作夥伴才需要這樣做)。(This is typically only required for partners supporting multiple tenants/organizations.)

    操作方法:To do so:

    1. 從應用程式刀鋒視窗中選擇 [資訊清單],這樣可開啟 [編輯資訊清單] 刀鋒視窗。Choose Manifest from the application blade, which opens the Edit Manifest blade.

      The Edit manifest blade

    2. availableToOtherTenants 的值變更為 trueChange the value of the availableToOtherTenants setting to true.

    3. 儲存您的變更。Save your changes.

Intune 權限範圍Intune permission scopes

Azure AD 和圖形 API 使用權限範圍來控制公司資源的存取權。Azure AD and the Graph API use permission scopes to control access to corporate resources.

權限範圍 (也稱為 OAuth 範圍) 可控制特定 Intune 實體和其內容的存取權。Permission scopes (also called the OAuth scopes) control access to specific Intune entities and their properties. 本節摘要說明 Intune 圖形 API 功能的權限範圍。This section summarizes the permission scopes for Intune Graph API features.

若要深入了解:To learn more:

當您將權限授與圖形 API 時,可以指定下列範圍來控制 Intune 功能的存取權:下表摘要說明 Intune 圖形 API 權限範圍。When you grant permission to the Graph API, you can specify the following scopes to control access to Intune features: The following table summarizes the Intune Graph API permission scopes. 第一欄顯示了出現在 Azure 入口網站中的功能名稱,第二欄提供權限範圍名稱。The first column shows the name of the feature as displayed in the Azure portal and the second column provides the permission scope name.

啟用存取_設定_Enable Access setting 領域名稱Scope name
在 Microsoft Intune 裝置上執行受使用者影響的遠端動作Perform user-impacting remote actions on Microsoft Intune devices DeviceManagementManagedDevices.PrivilegedOperations.AllDeviceManagementManagedDevices.PrivilegedOperations.All
讀取和寫入 Microsoft Intune 裝置Read and write Microsoft Intune devices DeviceManagementManagedDevices.ReadWrite.AllDeviceManagementManagedDevices.ReadWrite.All
讀取 Microsoft Intune 裝置Read Microsoft Intune devices DeviceManagementManagedDevices.Read.AllDeviceManagementManagedDevices.Read.All
讀取和寫入 Microsoft Intune RBAC 設定Read and write Microsoft Intune RBAC settings DeviceManagementRBAC.ReadWrite.AllDeviceManagementRBAC.ReadWrite.All
讀取 Microsoft Intune RBAC 設定Read Microsoft Intune RBAC settings DeviceManagementRBAC.Read.AllDeviceManagementRBAC.Read.All
讀取和寫入 Microsoft Intune 應用程式Read and write Microsoft Intune apps DeviceManagementApps.ReadWrite.AllDeviceManagementApps.ReadWrite.All
讀取 Microsoft Intune 應用程式Read Microsoft Intune apps DeviceManagementApps.Read.AllDeviceManagementApps.Read.All
讀取和寫入 Microsoft Intune 裝置設定和原則Read and write Microsoft Intune Device Configuration and Policies DeviceManagementConfiguration.ReadWrite.AllDeviceManagementConfiguration.ReadWrite.All
讀取 Microsoft Intune 裝置設定和原則Read Microsoft Intune Device Configuration and Policies DeviceManagementConfiguration.Read.AllDeviceManagementConfiguration.Read.All
讀取和寫入 Microsoft Intune 設定Read and write Microsoft Intune configuration DeviceManagementServiceConfig.ReadWrite.AllDeviceManagementServiceConfig.ReadWrite.All
讀取 Microsoft Intune 設定Read Microsoft Intune configuration DeviceManagementServiceConfig.Read.AllDeviceManagementServiceConfig.Read.All

表格依照 Azure 入口網站中顯示的順序列出設定。The table lists the settings as they appear in the Azure portal. 以下幾節依字母順序說明範圍。The following sections describe the scopes in alphabetical order.

此時,所有 Intune 權限範圍都需要系統管理員存取權。At this time, all Intune permission scopes require administrator access. 這表示執行存取 Intune 圖形 API 資源的應用程式或指令碼時,需要對應的認證。This means you need corresponding credentials when running apps or scripts that access Intune Graph API resources.

DeviceManagementApps.Read.AllDeviceManagementApps.Read.All

  • 啟用存取設定:讀取 Microsoft Intune 應用程式Enable Access setting: Read Microsoft Intune apps

  • 允許下列實體內容和狀態的讀取存取權:Permits read access to the following entity properties and status:

    • 行動裝置應用程式Mobile Apps
    • 行動裝置應用程式類別Mobile App Categories
    • 應用程式保護原則App Protection Policies
    • 應用程式設定App Configurations

DeviceManagementApps.ReadWrite.AllDeviceManagementApps.ReadWrite.All

  • 啟用存取設定:讀取和寫入 Microsoft Intune 應用程式Enable Access setting: Read and write Microsoft Intune apps

  • 可允許與 DeviceManagementApps.Read.All 相同的作業Allows the same operations as DeviceManagementApps.Read.All

  • 也可允許變更下列實體:Also permits changes to the following entities:

    • 行動裝置應用程式Mobile Apps
    • 行動裝置應用程式類別Mobile App Categories
    • 應用程式保護原則App Protection Policies
    • 應用程式設定App Configurations

DeviceManagementConfiguration.Read.AllDeviceManagementConfiguration.Read.All

  • 啟用存取設定:讀取 Microsoft Intune 裝置設定和原則Enable Access setting: Read Microsoft Intune device configuration and policies

  • 允許下列實體內容和狀態的讀取存取權:Permits read access to the following entity properties and status:

    • 裝置設定Device Configuration
    • 裝置合規性原則Device Compliance Policy
    • 通知訊息Notification Messages

DeviceManagementConfiguration.ReadWrite.AllDeviceManagementConfiguration.ReadWrite.All

  • 啟用存取設定:讀取和寫入 Microsoft Intune 裝置設定和原則Enable Access setting: Read and write Microsoft Intune device configuration and policies

  • 可允許與 DeviceManagementConfiguration.Read.All 相同的作業Allows the same operations as DeviceManagementConfiguration.Read.All

  • 應用程式也可建立、指派、刪除及變更下列實體:Apps can also create, assign, delete, and change the following entities:

    • 裝置設定Device Configuration
    • 裝置合規性原則Device Compliance Policy
    • 通知訊息Notification Messages

DeviceManagementManagedDevices.PrivilegedOperations.AllDeviceManagementManagedDevices.PrivilegedOperations.All

  • 啟用存取設定:在 Microsoft Intune 裝置上執行受使用者影響的遠端動作Enable Access setting: Perform user-impacting remote actions on Microsoft Intune devices

  • 允許在受管理的裝置上執行下列遠端動作:Permits the following remote actions on a managed device:

    • 淘汰Retire
    • 抹除Wipe
    • 重設/復原密碼Reset/Recover Passcode
    • 遠端鎖定Remote Lock
    • 啟用/停用遺失模式Enable/Disable Lost Mode
    • 清理電腦Clean PC
    • 重新開機Reboot
    • 從共用的裝置刪除使用者Delete User from Shared Device

DeviceManagementManagedDevices.Read.AllDeviceManagementManagedDevices.Read.All

  • 啟用存取設定:讀取 Microsoft Intune 裝置Enable Access setting: Read Microsoft Intune devices

  • 允許下列實體內容和狀態的讀取存取權:Permits read access to the following entity properties and status:

    • 受管理的裝置Managed Device
    • 裝置類別Device Category
    • 偵測到的應用程式Detected App
    • 遠端動作Remote actions
    • 惡意程式碼資訊Malware information

DeviceManagementManagedDevices.ReadWrite.AllDeviceManagementManagedDevices.ReadWrite.All

  • 啟用存取設定:讀取和寫入 Microsoft Intune 裝置Enable Access setting: Read and write Microsoft Intune devices

  • 可允許與 DeviceManagementManagedDevices.Read.All 相同的作業Allows the same operations as DeviceManagementManagedDevices.Read.All

  • 應用程式也可建立、刪除及變更下列實體:Apps can also create, delete, and change the following entities:

    • 受管理的裝置Managed Device
    • 裝置類別Device Category
  • 此外,也允許下列遠端動作:The following remote actions are also allowed:

    • 尋找裝置Locate devices
    • 略過啟用鎖定Bypass activation lock
    • 要求遠端協助Request remote assistance

DeviceManagementRBAC.Read.AllDeviceManagementRBAC.Read.All

  • 啟用存取設定:讀取 Microsoft Intune RBAC 設定Enable Access setting: Read Microsoft Intune RBAC settings

  • 允許下列實體內容和狀態的讀取存取權:Permits read access to the following entity properties and status:

    • 角色指派Role Assignments
    • 角色定義Role Definitions
    • 資源作業Resource Operations

DeviceManagementRBAC.ReadWrite.AllDeviceManagementRBAC.ReadWrite.All

  • 啟用存取設定:讀取和寫入 Microsoft Intune RBAC 設定Enable Access setting: Read and write Microsoft Intune RBAC settings

  • 可允許與 DeviceManagementRBAC.Read.All 相同的作業Allows the same operations as DeviceManagementRBAC.Read.All

  • 應用程式也可建立、指派、刪除及變更下列實體:Apps can also create, assign, delete, and change the following entities:

    • 角色指派Role Assignments
    • 角色定義Role Definitions

DeviceManagementServiceConfig.Read.AllDeviceManagementServiceConfig.Read.All

  • 啟用存取設定:讀取 Microsoft Intune 設定Enable Access setting: Read Microsoft Intune configuration

  • 允許下列實體內容和狀態的讀取存取權:Permits read access to the following entity properties and status:

    • 註冊裝置Device Enrollment
    • Apple 推播通知憑證Apple Push Notification Certificate
    • Apple 裝置註冊方案Apple Device Enrollment Program
    • Apple 大量採購方案Apple Volume Purchase Program
    • Exchange ConnectorExchange Connector
    • 條款及條件Terms and Conditions
    • 電信費用管理Telecoms Expense Management
    • 雲端 PKICloud PKI
    • 商標Branding
    • Mobile Threat DefenseMobile Threat Defense

DeviceManagementServiceConfig.ReadWrite.AllDeviceManagementServiceConfig.ReadWrite.All

  • 啟用存取設定:讀取和寫入 Microsoft Intune 設定Enable Access setting: Read and write Microsoft Intune configuration

  • 可允許與 DeviceManagementServiceConfig.Read.All_ 相同的作業Allows the same operations as DeviceManagementServiceConfig.Read.All_

  • 應用程式也可以設定下列 Intune 功能:Apps can also configure the following Intune features:

    • 註冊裝置Device Enrollment
    • Apple 推播通知憑證Apple Push Notification Certificate
    • Apple 裝置註冊方案Apple Device Enrollment Program
    • Apple 大量採購方案Apple Volume Purchase Program
    • Exchange ConnectorExchange Connector
    • 條款及條件Terms and Conditions
    • 電信費用管理Telecoms Expense Management
    • 雲端 PKICloud PKI
    • 商標Branding
    • Mobile Threat DefenseMobile Threat Defense

Azure AD 驗證範例Azure AD authentication examples

本節說明如何將 Azure AD 整合到您的 C# 和 PowerShell 專案中。This section shows how to incorporate Azure AD into your C# and PowerShell projects.

在每個範例中,您都必須指定至少具有 DeviceManagementManagedDevices.Read.All 權限範圍的應用程式識別碼 (稍早曾討論過)。In each example, you'll need to specify an application ID that has at least the DeviceManagementManagedDevices.Read.All permission scope (discussed earlier).

測試任一範例時,您可能會收到類似以下這樣的 HTTP 狀態 403 (禁止) 錯誤:When testing either example, you may receive HTTP status 403 (Forbidden) errors similar to the following:

{
  "error": {
    "code": "Forbidden",
    "message": "Application is not authorized to perform this operation - Operation ID " +
       "(for customer support): 00000000-0000-0000-0000-000000000000 - " +
       "Activity ID: cc7fa3b3-bb25-420b-bfb2-1498e598ba43 - " +
       "Url: https://example.manage.microsoft.com/" +
       "Service/Resource/RESTendpoint?" +
       "api-version=2017-03-06 - CustomApiErrorPhrase: ",
    "innerError": {
      "request-id": "00000000-0000-0000-0000-000000000000",
      "date": "1980-01-0112:00:00"
    }
  }
}

如果發生這種情況,請確認:If this happens, verify that:

  • 您已將應用程式識別碼更新為已獲授權可使用圖形 API 和 DeviceManagementManagedDevices.Read.All 權限範圍。You've updated the application ID to one authorized to use the Graph API and the DeviceManagementManagedDevices.Read.All permission scope.

  • 您的租用戶認證支援系統管理功能。Your tenant credentials support administrative functions.

  • 您的程式碼與所顯示的範例相似。Your code is similar to the displayed samples.

在 C# 中驗證 Azure ADAuthenticate Azure AD in C#

這個範例示範如何使用 C# 來擷取與您的 Intune 帳戶相關聯的裝置清單。This example shows how to use C# to retrieve a list of devices associated with your Intune account.

  1. 啟動 Visual Studio,然後建立新的 Visual C# 主控台應用程式 (.NET Framework) 專案。Start Visual Studio and then create a new Visual C# Console app (.NET Framework) project.

  2. 輸入專案的名稱,然後依需要提供其他詳細資料。Enter a name for your project and provide other details as desired.

    Creating a C# console app project in Visual Studio

  3. 使用 [方案總管] 將 Microsoft ADAL NuGet 套件加入至專案。Use the Solution Explorer to add the Microsoft ADAL NuGet package to the project.

    1. 在 [方案總管] 上按一下滑鼠右鍵。Right-click the Solution Explorer.
    2. 選擇 [管理 NuGet 套件...]Choose Manage NuGet Packages… > [瀏覽]。> Browse.
    3. 然後依序選擇 Microsoft.IdentityModel.Clients.ActiveDirectory 和 [安裝]。Select Microsoft.IdentityModel.Clients.ActiveDirectory and then choose Install.

    Selecting the Azure AD identity model module

  4. 將下列陳述式加入至 Program.cs 頂端:Add the following statements to the top of Program.cs:

    using Microsoft.IdentityModel.Clients.ActiveDirectory;</p>
    using System.Net.Http;
    
  5. 加入建立授權標頭的方法:Add a method to create the authorization header:

    private static async Task<string> GetAuthorizationHeader()
    {
        string applicationId = "<Your Application ID>";
        string authority = "https://login.microsoftonline.com/common/";
        Uri redirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob");
        AuthenticationContext context = new AuthenticationContext(authority);
        AuthenticationResult result = await context.AcquireTokenAsync(
            "https://graph.microsoft.com",
            applicationId, redirectUri,
            new PlatformParameters(PromptBehavior.Auto));
        return result.CreateAuthorizationHeader();
    

    請記得變更 application_ID 的值以符合在至少 DeviceManagementManagedDevices.Read.All 權限範圍授與的內容,如前所述。Remember to change the value of application_ID to match one granted at least the DeviceManagementManagedDevices.Read.All permission scope, as described earlier.

  6. 加入擷取裝置清單的方法:Add a method to retrieve the list of devices:

    private static async Task<string> GetMyManagedDevices()
    {
        string authHeader = await GetAuthorizationHeader();
        HttpClient graphClient = new HttpClient();
        graphClient.DefaultRequestHeaders.Add("Authorization", authHeader);
        return await graphClient.GetStringAsync(
            "https://graph.microsoft.com/beta/me/managedDevices");
    }
    
  7. 更新 Main 以呼叫 GetMyManagedDevicesUpdate Main to call GetMyManagedDevices:

    string devices = GetMyManagedDevices().GetAwaiter().GetResult();
    Console.WriteLine(devices);
    
  8. 編譯並執行您的程式。Compile and run your program.

當您第一次執行程式時,應該會收到兩個提示。When you first run your program, you should receive two prompts. 第一個提示會要求您提供認證,第二個提示會授與 managedDevices 要求的權限。The first requests your credentials and the second grants permissions for the managedDevices request.

如需參考,以下是已完成的程式:For reference, here's the completed program:

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace IntuneGraphExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string devices = GetMyManagedDevices().GetAwaiter().GetResult();
            Console.WriteLine(devices);
        }

        private static async Task<string> GetAuthorizationHeader()
        {
            string applicationId = "<Your Application ID>";
            string authority = "https://login.microsoftonline.com/common/";
            Uri redirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob");
            AuthenticationContext context = new AuthenticationContext(authority);
            AuthenticationResult result = await context.AcquireTokenAsync("https://graph.microsoft.com", applicationId, redirectUri, new PlatformParameters(PromptBehavior.Auto));
            return result.CreateAuthorizationHeader();
        }

        private static async Task<string> GetMyManagedDevices()
        {
            string authHeader = await GetAuthorizationHeader();
            HttpClient graphClient = new HttpClient();
            graphClient.DefaultRequestHeaders.Add("Authorization", authHeader);
            return await graphClient.GetStringAsync("https://graph.microsoft.com/beta/me/managedDevices");
        }
    }
}

驗證 Azure AD (PowerShell)Authenticate Azure AD (PowerShell)

下列 PowerShell 指令碼使用 AzureAD PowerShell 模組來進行驗證。The following PowerShell script uses the AzureAD PowerShell module for authentication. 若要深入了解,請參閱 Azure Active Directory PowerShell 第 2 版 (英文) 和 Intune PowerShell 範例 (英文)。To learn more, see Azure Active Directory PowerShell Version 2 and the Intune PowerShell examples.

在此範例中,更新 $clientID 的值以符合有效的應用程式識別碼。In this example, update the value of $clientID to match a valid application ID.

function Get-AuthToken {
    [cmdletbinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        $User
    )

    $userUpn = New-Object "System.Net.Mail.MailAddress" -ArgumentList $User
    $tenant = $userUpn.Host

    Write-Host "Checking for AzureAD module..."

    $AadModule = Get-Module -Name "AzureAD" -ListAvailable
    if ($AadModule -eq $null) {
        Write-Host "AzureAD PowerShell module not found, looking for AzureADPreview"
        $AadModule = Get-Module -Name "AzureADPreview" -ListAvailable
    }

    if ($AadModule -eq $null) {
        write-host
        write-host "AzureAD Powershell module not installed..." -f Red
        write-host "Install by running 'Install-Module AzureAD' or 'Install-Module AzureADPreview' from an elevated PowerShell prompt" -f Yellow
        write-host "Script can't continue..." -f Red
        write-host
        exit
    }

    # Getting path to ActiveDirectory Assemblies
    # If the module count is greater than 1 find the latest version

    if ($AadModule.count -gt 1) {
        $Latest_Version = ($AadModule | select version | Sort-Object)[-1]
        $aadModule = $AadModule | ? { $_.version -eq $Latest_Version.version }
        $adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
        $adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
    }

    else {
        $adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
        $adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
    }

    [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
    [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

    $clientId = "<Your Application ID>"
    $redirectUri = "urn:ietf:wg:oauth:2.0:oob"
    $resourceAppIdURI = "https://graph.microsoft.com"
    $authority = "https://login.microsoftonline.com/$Tenant"

    try {
        $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
        # https://msdn.microsoft.com/library/azure/microsoft.identitymodel.clients.activedirectory.promptbehavior.aspx
        # Change the prompt behaviour to force credentials each time: Auto, Always, Never, RefreshSession
        $platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto"
        $userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($User, "OptionalDisplayableId")
        $authResult = $authContext.AcquireTokenAsync($resourceAppIdURI, $clientId, $redirectUri, $platformParameters, $userId).Result
        # If the accesstoken is valid then create the authentication header
        if ($authResult.AccessToken) {
            # Creating header for Authorization token
            $authHeader = @{
                'Content-Type' = 'application/json'
                'Authorization' = "Bearer " + $authResult.AccessToken
                'ExpiresOn' = $authResult.ExpiresOn
            }
            return $authHeader
        }
        else {
            Write-Host
            Write-Host "Authorization Access Token is null, please re-run authentication..." -ForegroundColor Red
            Write-Host
            break
        }
    }
    catch {
        write-host $_.Exception.Message -f Red
        write-host $_.Exception.ItemName -f Red
        write-host
        break
    }   
}

$authToken = Get-AuthToken -User "<Your AAD Username>"

try {
    $uri = "https://graph.microsoft.com/beta/me/managedDevices"
    Write-Verbose $uri
    (Invoke-RestMethod -Uri $uri –Headers $authToken –Method Get).Value
}
catch {
    $ex = $_.Exception
    $errorResponse = $ex.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($errorResponse)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    Write-Host "Response content:`n$responseBody" -f Red
    Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
    write-host
    break
}

支援多個租用戶和合作夥伴Support multiple tenants and partners

如果您的組織支援的組織具有自己的 Azure AD 租用戶,您可能會想要允許用戶端以其各自的租用戶使用應用程式。If your organization supports organizations with their own Azure AD tenants, you may want to permit your clients to use your application with their respective tenants.

操作方法:To do so:

  1. 確認用戶端帳戶存在於目標 Azure AD 租用戶中。Verify that the client account exists in the target Azure AD tenant.

  2. 確認您的租用戶帳戶允許使用者註冊應用程式 (請參閱使用者設定)。Verify that your tenant account allows users to register applications (see User settings).

  3. 建立每個租用戶之間的關聯性。Establish a relationship between each tenant.

    若要這樣做,請:To do so, either:

    a.a. 使用 Microsoft 合作夥伴中心 來定義與您的用戶端及其電子郵件地址之間的關聯性。Use the Microsoft Partner Center to define a relationship with your client and their email address.

    b。b. 邀請使用者成為您租用戶的來賓。Invite the user to become a guest of your tenant.

若要邀請使用者成為您租用戶的來賓:To invite the user to be a guest of your tenant:

  1. 從 [快速工作] 面板中選擇 [新增來賓使用者]。Choose Add a guest user from the Quick tasks panel.

    Use Quick Tasks to add a guest user

  2. 輸入用戶端的電子郵件地址及 (選擇性) 新增用來邀請的個人化訊息。Enter the client's email address and (optionally) add a personalized message for the invite.

    Inviting an external user as a guest

  3. 選擇 [邀請]。Choose Invite.

這樣便會將邀請傳送給使用者。This sends an invite to the user.

A sample guest invitation

使用者需要選擇 [開始] 連結接受您的邀請。The user needs to choose the Get Started link to accept your invitation.

建立關聯性 (或接受您的邀請) 之後,將使用者帳戶加入 [目錄角色]。When the relationship is established (or your invitation has been accepted), add the user account to the Directory role.

請記住要視需要將使用者加入其他角色。Remember to add the user to other roles as needed. 比方說,若要允許使用者管理 Intune 設定,它們必須是全域管理員Intune 服務管理員For example, to allow the user to manage Intune settings, they need to be either a Global Administrator or an Intune Service administrator.

此外:Also:

  • 您可以使用 http://portal.office.com,將 Intune 授權指派給您的使用者帳戶。Use http://portal.office.com to assign an Intune license to your user account.

  • 更新應用程式碼以驗證用戶端的 Azure AD 租用戶網域,而不只是您自己的網域。Update application code to authenticate to the client's Azure AD tenant domain, rather than your own.

    例如,假設您的租用戶網域為 contosopartner.onmicrosoft.com,用戶端的租用戶網域是 northwind.onmicrosoft.com,您會更新程式碼來驗證您用戶端的租用戶。For example, suppose your tenant domain is contosopartner.onmicrosoft.com and your client's tenant domain is northwind.onmicrosoft.com, you would update your code to authenticate to your client's tenant.

    若要根據先前的範例在 C# 應用程式中這樣做,您會變更 authority 變數的值:To do so in a C# application based on the earlier example, you'd change the value of the authority variable:

    string authority = "https://login.microsoftonline.com/common/";
    

    to

    string authority = "https://login.microsoftonline.com/northwind.onmicrosoft.com/";