建立應用程式以存取沒有使用者的 Microsoft 365 DefenderCreate an app to access Microsoft 365 Defender without a user


已改善的 Microsoft 365 安全性中心 現在已提供公開預覽。The improved Microsoft 365 security center is now available in public preview. 這種新的經驗會將 Defender、Office 365 的 Defender、Microsoft 365 Defender 等,帶入 Microsoft 365 的安全性中心。This new experience brings Defender for Endpoint, Defender for Office 365, Microsoft 365 Defender, and more into the Microsoft 365 security center. 安全小組現在可以管理所有端點、電子郵件及跨產品調查、設定和修正,而不需要流覽個別的產品入口網站。Security teams can now manage all endpoint, email and cross product investigations, configuration and remediation without the need to navigate to separate product portals. 深入瞭解已變更的專案。Learn more about what's changed.

適用於:Applies to:

  • Microsoft 365 DefenderMicrosoft 365 Defender


一些與 prereleased 產品相關的資訊,在正式發行之前,可能會受到大量修改。Some information relates to prereleased product which may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.Microsoft makes no warranties, express or implied, with respect to the information provided here.

此頁面說明如何建立應用程式,以在沒有定義的使用者的情況下,取得 Microsoft 365 Defender 的程式存取權,例如,如果您要建立守護程式或後臺服務。This page describes how to create an application to get programmatic access to Microsoft 365 Defender without a defined user—for example, if you're creating a daemon or background service.

如果您需要以程式設計方式代替一或多個使用者存取 Microsoft 365 Defender,請參閱 create a app to an a app to Access microsoft 365 Defender APIs 代表使用者 ,並 建立具有對 Microsoft 365 Defender APIs 的合作夥伴存取的應用程式If you need programmatic access to Microsoft 365 Defender on behalf of one or more users, see Create an app to access Microsoft 365 Defender APIs on behalf of a user and Create an app with partner access to Microsoft 365 Defender APIs. 如果您不確定需要哪種類型的存取,請參閱 入門If you're not sure which kind of access you need, see Get started.

Microsoft 365 Defender 會透過一組程式設計 APIs 來公開其大部分資料和動作。Microsoft 365 Defender exposes much of its data and actions through a set of programmatic APIs. 這些 APIs 可協助您自動化工作流程,並使用 Microsoft 365 Defender 的功能。Those APIs help you automate workflows and make use of Microsoft 365 Defender's capabilities. 此 API access 需要 OAuth 2.0 驗證。This API access requires OAuth2.0 authentication. 如需詳細資訊,請參閱 OAuth 2.0 授權碼流程For more information, see OAuth 2.0 Authorization Code Flow.

一般來講,您必須採取下列步驟,才能使用這些 APIs:In general, you'll need to take the following steps to use these APIs:

  • 建立 Azure Active Directory (Azure AD) 應用程式。Create an Azure Active Directory (Azure AD) application.
  • 使用此應用程式取得存取權杖。Get an access token using this application.
  • 使用權杖來存取 Microsoft 365 Defender API。Use the token to access Microsoft 365 Defender API.

本文將說明如何:This article explains how to:

  • 建立 Azure AD 應用程式Create an Azure AD application
  • 取得 Microsoft 365 Defender 的存取權杖Get an access token to Microsoft 365 Defender
  • 驗證權杖。Validate the token.

建立應用程式Create an app

  1. 全域系統管理員 角色的使用者身分登入 AzureSign in to Azure as a user with the Global Administrator role.

  2. 流覽至 [ Azure Active Directory > 應用程式註冊] > 新註冊Navigate to Azure Active Directory > App registrations > New registration.

    Microsoft Azure 的影像及應用程式註冊導覽

  3. 在表單中,選擇應用程式的名稱,然後選取 [ 註冊]。In the form, choose a name for your application, then select Register.

  4. 在 [應用程式] 頁面上,選取 [ API 許可權 > 新增許可權 > APIs 我的組織使用>],輸入 microsoft 威脅防護,然後選取 [ microsoft 威脅防護]。On your application page, select API Permissions > Add permission > APIs my organization uses >, type Microsoft Threat Protection, and select Microsoft Threat Protection. 您的應用程式現在可以存取 Microsoft 365 Defender。Your app can now access Microsoft 365 Defender.


    Microsoft 威脅防護 是 Microsoft 365 Defender 的先前名稱,因此不會出現在原始清單中。Microsoft Threat Protection is a former name for Microsoft 365 Defender, and will not appear in the original list. 您必須先在文字方塊中寫入其名稱,才能看到顯示的名稱。You need to start writing its name in the text box to see it appear.

    API 許可權選取的影像

  5. 選取 [ 應用程式許可權]。Select Application permissions. 為您的案例選擇相關許可權 (例如, Incident。 Read。 All) ,然後選取 [ 新增許可權]。Choose the relevant permissions for your scenario (for example, Incident.Read.All), and then select Add permissions.

    API 存取和 API 選取的影像


    您必須選取案例的相關許可權。You need to select the relevant permissions for your scenario. 讀取所有的事件 只是一個範例。Read all incidents is just an example. 若要決定您需要的許可權,請參閱您想要呼叫之 API 中的 [ 許可權 ] 區段。To determine which permission you need, please look at the Permissions section in the API you want to call.

    例如,若要 執行高級查詢,請選取「執行高級查詢」許可權;若要 隔離裝置,請選取「隔離電腦」許可權。For instance, to run advanced queries, select the 'Run advanced queries' permission; to isolate a device, select the 'Isolate machine' permission.

  6. 選取 [授與系統管理員同意]。Select Grant admin consent. 每次您新增許可權時,都必須選取 [授與系統管理員同意 ],才會生效。Every time you add a permission, you must select Grant admin consent for it to take effect.


  7. 若要將機密新增至應用程式,請選取 [ 憑證 & 密碼],新增描述至密碼,然後選取 [ 新增]。To add a secret to the application, select Certificates & secrets, add a description to the secret, then select Add.


    選取 [ 新增] 之後,選取 [複製產生的機密值]。After you select Add, select copy the generated secret value. 離開後,您將無法取得密碼值。You won't be able to retrieve the secret value after you leave.


  8. 將您的應用程式識別碼和租使用者識別碼記錄在安全的位置。Record your application ID and your tenant ID somewhere safe. 在 [應用程式] 頁面的 [一覽 ] 底下會列出它們。They're listed under Overview on your application page.


  9. 僅適用于 microsoft 365 Defender 合作夥伴請遵循下列指示 ,透過 microsoft 365 Defender APIs 取得合作夥伴存取權,將您的應用程式設定為多租使用者,以便在您收到系統管理員同意後,可在所有承租人中使用。For Microsoft 365 Defender Partners only: Follow these instructions for partner access through the Microsoft 365 Defender APIs, set your app to be multi-tenant, so it can be available in all tenants once you receive admin consent. 協力廠商應用程式 需要 合作夥伴存取,例如,如果您要建立的應用程式要在多個客戶的承租人中執行。Partner access is required for third-party apps—for example, if you create an app that is intended to run in multiple customers' tenants. 如果您建立只想要在租使用者中執行的服務(例如您自己使用的應用程式,只會與您自己的資料互動),就 不需要 這樣做。It is not required if you create a service that you want to run in your tenant only, such as an application for your own usage that will only interact with your own data. 若要將您的應用程式設為多租使用者:To set your app to be multi-tenant:

    • 移至 [ 驗證],然後新增 https://portal.azure.com 為重新 導向 URIGo to Authentication, and add https://portal.azure.com as the Redirect URI.

    • 在頁面底部的 [ 支援的帳戶類型] 底下,選取您的多租使用者應用程式的 任何組織目錄 應用程式中的帳戶。On the bottom of the page, under Supported account types, select the Accounts in any organizational directory application consent for your multi-tenant app.

    因為您的應用程式代表您的使用者與 Microsoft 365 Defender 互動,所以需要針對您想要使用它的每一個承租人進行核准。Since your application interacts with Microsoft 365 Defender on behalf of your users, it needs be approved for every tenant on which you intend to use it.

    每個租使用者的 Active Directory 全域系統管理員都必須選取同意連結並核准您的應用程式。The Active Directory global admin for each tenant needs to select the consent link and approve your app.

    同意連結的結構如下:The consent link has the following structure:


    00000000-0000-0000-0000-000000000000應以您的應用程式識別碼取代位數。The digits 00000000-0000-0000-0000-000000000000 should be replaced with your Application ID.

做!Done! 您已成功註冊應用程式!You've successfully registered an application! 請參閱下列範例以取得及驗證權杖。See examples below for token acquisition and validation.

取得存取權杖Get an access token

如需 Azure Active Directory 標記的詳細資訊,請參閱 AZURE AD 教學課程。For more information on Azure Active Directory tokens, see the Azure AD tutorial.


雖然本節中的範例會鼓勵您貼上用於測試目的的機密值,否則您 不應該將機密硬編碼 成實際執行中執行的應用程式。Although the examples in this section encourage you to paste in secret values for testing purposes, you should never hardcode secrets into an application running in production. 協力廠商可以使用您的機密存取資源。A third party could use your secret to access resources. 您可以使用 Azure Key Vault,協助保護應用程式的機密。You can help keep your app's secrets secure by using Azure Key Vault. 如需如何保護應用程式的實際範例,請參閱 使用 Azure Key Vault 管理伺服器應用程式中的機密For a practical example of how you can protect your app, see Manage secrets in your server apps with Azure Key Vault.

使用 PowerShell 取得存取權杖Get an access token using PowerShell

# This code gets the application context token and saves it to a file named "Latest-token.txt" under the current directory.

$tenantId = '' # Paste your directory (tenant) ID here
$clientId = '' # Paste your application (client) ID here
$appSecret = '' # Paste your own app secret here to test, then store it in a safe place, such as the Azure Key Vault!

$resourceAppIdUri = 'https://api.security.microsoft.com'
$oAuthUri = "https://login.windows.net/$tenantId/oauth2/token"

$authBody = [Ordered] @{
    resource = $resourceAppIdUri
    client_id = $clientId
    client_secret = $appSecret
    grant_type = 'client_credentials'

$authResponse = Invoke-RestMethod -Method Post -Uri $oAuthUri -Body $authBody -ErrorAction Stop
$token = $authResponse.access_token

Out-File -FilePath "./Latest-token.txt" -InputObject $token

return $token

使用 C 取得存取 token#Get an access token using C#


下列程式碼已使用 Nuget Windows.identitymodel.extensions.dll 進行測試。 ActiveDirectory 3.19.8。The following code was tested with Nuget Microsoft.IdentityModel.Clients.ActiveDirectory 3.19.8.

  1. 建立新的主控台應用程式。Create a new console application.

  2. 安裝 NuGet windows.identitymodel.extensions.dll。 ActiveDirectoryInstall NuGet Microsoft.IdentityModel.Clients.ActiveDirectory.

  3. 新增下列行:Add the following line:

    using Microsoft.IdentityModel.Clients.ActiveDirectory;
  4. 將下列程式碼複製並貼到您的應用程式中 (不要忘記更新這三個變數: tenantIdclientIdappSecret) :Copy and paste the following code into your app (don't forget to update the three variables: tenantId, clientId, appSecret):

    string tenantId = ""; // Paste your directory (tenant) ID here
    string clientId = ""; // Paste your application (client) ID here
    string appSecret = ""; // Paste your own app secret here to test, then store it in a safe place, such as the Azure Key Vault!
    const string authority = "https://login.windows.net";
    const string wdatpResourceId = "https://api.security.microsoft.com";
    AuthenticationContext auth = new AuthenticationContext($"{authority}/{tenantId}/");
    ClientCredential clientCredential = new ClientCredential(clientId, appSecret);
    AuthenticationResult authenticationResult = auth.AcquireTokenAsync(wdatpResourceId, clientCredential).GetAwaiter().GetResult();
    string token = authenticationResult.AccessToken;

使用 Python 取得存取權杖Get an access token using Python

import json
import urllib.request
import urllib.parse

tenantId = '' # Paste your directory (tenant) ID here
clientId = '' # Paste your application (client) ID here
appSecret = '' # Paste your own app secret here to test, then store it in a safe place, such as the Azure Key Vault!

url = "https://login.windows.net/%s/oauth2/token" % (tenantId)

resourceAppIdUri = 'https://api.securitycenter.windows.com'

body = {
    'resource' : resourceAppIdUri,
    'client_id' : clientId,
    'client_secret' : appSecret,
    'grant_type' : 'client_credentials'

data = urllib.parse.urlencode(body).encode("utf-8")

req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
aadToken = jsonResponse["access_token"]

使用曲線取得存取權杖Get an access token using curl


在 Windows 10 版本1803和更新版本上都預先安裝了卷。Curl is pre-installed on Windows 10, versions 1803 and later. 若為其他版本的 Windows,請直接從 官方卷網站下載並安裝工具。For other versions of Windows, download and install the tool directly from the official curl website.

  1. 開啟命令提示字元,並將 CLIENT_ID 設定為您的 Azure 應用程式識別碼。Open a command prompt, and set CLIENT_ID to your Azure application ID.

  2. 將 CLIENT_SECRET 設定為您的 Azure 應用程式密碼。Set CLIENT_SECRET to your Azure application secret.

  3. 將 TENANT_ID 設定為要使用您的應用程式存取 Microsoft 365 Defender 之客戶的 Azure 租使用者識別碼。Set TENANT_ID to the Azure tenant ID of the customer that wants to use your app to access Microsoft 365 Defender.

  4. 執行下列命令:Run the following command:

    curl -i -X POST -H "Content-Type:application/x-www-form-urlencoded" -d "grant_type=client_credentials" -d "client_id=%CLIENT_ID%" -d "scope=https://securitycenter.onmicrosoft.com/windowsatpservice/.default" -d "client_secret=%CLIENT_SECRET%" "https://login.microsoftonline.com/%TENANT_ID%/oauth2/v2.0/token" -k

    成功的回應如下所示:A successful response will look like this:

    {"token_type":"Bearer","expires_in":3599,"ext_expires_in":0,"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIn <truncated> aWReH7P0s0tjTBX8wGWqJUdDA"}

驗證 tokenValidate the token

  1. 將權杖複製並貼到 JSON web token 驗證者網站(JWT) 以進行解碼。Copy and paste the token into the JSON web token validator website, JWT, to decode it.

  2. 請確定已解碼權杖中的 角色 宣告包含所需的許可權。Make sure that the roles claim within the decoded token contains the desired permissions.

    在下列影像中,您可以看到從應用程式取得的解碼標記,具有 Incidents.Read.AllIncidents.ReadWrite.AllAdvancedHunting.Read.All 許可權:In the following image, you can see a decoded token acquired from an app, with Incidents.Read.All, Incidents.ReadWrite.All, and AdvancedHunting.Read.All permissions:


使用權杖來存取 Microsoft 365 Defender APIUse the token to access the Microsoft 365 Defender API

  1. 選擇您想要使用 (事件或「高級搜尋) 的 API。Choose the API you want to use (incidents, or advanced hunting). 如需詳細資訊,請參閱 支援的 Microsoft 365 Defender APIsFor more information, see Supported Microsoft 365 Defender APIs.

  2. 在您要傳送的 HTTP 要求中,將授權標頭設定為 "Bearer" <token>持有 者為授權配置,而 token 為您驗證的權杖。In the http request you are about to send, set the authorization header to "Bearer" <token>, Bearer being the authorization scheme, and token being your validated token.

  3. 權杖會在一小時內到期。The token will expire within one hour. 在此期間,您可以使用相同的權杖傳送一個以上的要求。You can send more than one request during this time with the same token.

下列範例顯示如何 使用 c # 傳送要求以取得事件清單。The following example shows how to send a request to get a list of incidents using C#.

    var httpClient = new HttpClient();
    var request = new HttpRequestMessage(HttpMethod.Get, "https://api.security.microsoft.com/api/incidents");

    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var response = httpClient.SendAsync(request).GetAwaiter().GetResult();