创建应用以在没有用户的情况下访问 Microsoft 365 DefenderCreate an app to access Microsoft 365 Defender without a user


改进的 Microsoft 365 安全中心现在可用。The improved Microsoft 365 security center is now available. 此新体验将 Defender for Endpoint、Defender for Office、365 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. 了解新增功能Learn what's new.

适用于:Applies to:

  • Microsoft 365 DefenderMicrosoft 365 Defender


某些信息与预发布的产品有关,在商业发布之前可能有重大修改。Some information relates to prereleased product which may be substantially modified before it's commercially released. Microsoft 对此处所提供的信息不作任何明示或默示的保证。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,请参阅创建应用以代表用户访问 Microsoft 365 Defender API 和 创建具有 Microsoft 365 Defender API合作伙伴访问权限的应用。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 通过一组编程 API 公开其大部分数据和操作。Microsoft 365 Defender exposes much of its data and actions through a set of programmatic APIs. 这些 API 可帮助你自动化工作流和利用 Microsoft 365 Defender 的功能。Those APIs help you automate workflows and make use of Microsoft 365 Defender's capabilities. 此 API 访问需要 OAuth2.0 身份验证。This API access requires OAuth2.0 authentication. 有关详细信息,请参阅 OAuth 2.0 授权代码流For more information, see OAuth 2.0 Authorization Code Flow.

通常,你将需要执行以下步骤来使用这些 API: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. 以具有全局管理员角色的用户 登录 Azure。Sign 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 权限""添加我的组织使用> > > API",键入 "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. 在安全的地方记录应用程序 ID 和租户 ID。Record your application ID and your tenant ID somewhere safe. 它们列在应用程序 页面上的" 概述"下。They're listed under Overview on your application page.

    已创建应用 ID 的图像

  9. 仅适用于 Microsoft 365 Defender 合作伙伴:按照这些说明通过 Microsoft 365 Defender API 访问合作伙伴,将应用设置为多租户,以便应用在获得管理员同意后可在所有租户中可用。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 应替换为应用程序 ID。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 密钥保管库,可帮助保护 应用密钥的安全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 获取访问令牌#Get an access token using C#


以下代码已使用 Nuget Microsoft.IdentityModel.Clients.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 Microsoft.IdentityModel.Clients.ActiveDirectoryInstall NuGet Microsoft.IdentityModel.Clients.ActiveDirectory.

  3. 添加以下行:Add the following line:

    using Microsoft.IdentityModel.Clients.ActiveDirectory;
  4. 将以下代码复制并粘贴到应用中 (请不要忘记更新三个 tenantId clientId appSecret 变量:、、) :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.security.microsoft.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 应用程序 ID。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 租户 ID。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://api.security.microsoft.com/.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"}

验证令牌Validate the token

  1. 将令牌复制并粘贴到 JSON Web 令牌验证程序网站 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.All Incidents.ReadWrite.All AdvancedHunting.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 API。For more information, see Supported Microsoft 365 Defender APIs.

  2. 在即将发送的 http 请求中,将授权标头设置为 "Bearer" <token> ,Bearer 为授权方案,令牌为经过验证的令牌。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();