创建具有 Microsoft 365 Defender API 合作伙伴访问权限的应用Create an app with partner access to Microsoft 365 Defender APIs

重要

改进的 Microsoft 365 安全中心现已提供公共预览版。The improved Microsoft 365 security center is now available in public preview. 此新体验将 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. 安全团队现可管理所有终结点、电子邮件和跨产品调查、配置和修正,而无需导航到单独的产品门户。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

重要

某些信息与预发布的产品有关,在商业发布之前可能有重大修改。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 编程访问权限的 Azure Active Directory 应用。This page describes how to create an Azure Active Directory app that has programmatic access to Microsoft 365 Defender, on behalf of users across multiple tenants. 多租户应用可用于为大型用户组服务。Multi-tenant apps are useful for serving large groups of users.

如果你需要代表单个用户以编程方式访问 Microsoft 365 Defender,请参阅创建应用以代表用户访问Microsoft 365 Defender API。If you need programmatic access to Microsoft 365 Defender on behalf of a single user, see Create an app to access Microsoft 365 Defender APIs on behalf of a user. 如果需要在没有用户明确定义的 (的情况下访问,例如,如果你要编写后台应用或守护程序) ,请参阅创建应用以在没有用户的情况下访问Microsoft 365 Defender。If you need access without a user explicitly defined (for example, if you're writing a background app or daemon), see Create an app to access Microsoft 365 Defender without a user. 如果你不确定需要哪种类型的访问,请参阅 入门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.

由于此应用是多租户应用,你还需要代表其用户获得每个租户的管理员同意。Since this app is multi-tenant, you'll also need admin consent from each tenant on behalf of its users.

本文介绍如何:This article explains how to:

  • 创建 多租户 Azure AD 应用程序Create a multi-tenant Azure AD application
  • 获取应用程序的用户管理员授权,以访问 Microsoft 365 Defender 所需的资源。Get authorized consent from your user administrator for your application to access the Microsoft 365 Defender that resources it needs.
  • 获取 Microsoft 365 Defender 的访问令牌Get an access token to Microsoft 365 Defender
  • 验证令牌Validate the token

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 will help you automate work flows and innovate based on Microsoft 365 Defender capabilities. API 访问需要 OAuth2.0 身份验证。The 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 the APIs:

  • 创建 多租户 Azure AD 应用程序。Create a multi-tenant Azure AD application.
  • 获取 (同意) 管理员同意你的应用程序访问所需的 Microsoft 365 Defender 资源。Get authorized (consent) by your user administrator for your application to access Microsoft 365 Defender resources it needs.
  • 使用此应用程序获取访问令牌。Get an access token using this application.
  • 使用令牌访问 Microsoft 365 Defender API。Use the token to access Microsoft 365 Defender API.

以下步骤将指导你如何创建多租户 Azure AD 应用程序、获取 Microsoft 365 Defender 的访问令牌并验证令牌。The following steps with guide you how to create a multi-tenant Azure AD application, get an access token to Microsoft 365 Defender and validate the token.

创建多租户应用Create the multi-tenant 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 registration form:

    • 为应用程序选择一个名称。Choose a name for your application.
    • "支持的帐户类型"中,选择"任何组织目录中的帐户 (任何 Azure AD 目录) - 多租户"From Supported account types, select Accounts in any organizational directory (Any Azure AD directory) - Multitenant.
    • 填写重定向 URI 部分。Fill out the Redirect URI section. 选择类型 "Web", 将重定向 URI 作为 https://portal.azure.com 提供。Select type Web and give the redirect URI as https://portal.azure.com.

    填写完表单后,选择"注册 "。After you're done filling out the form, 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. 将应用程序添加到用户的租户。Add the application to your user's tenant.

    由于你的应用程序代表你的用户与 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.

    用户租户 中的全局管理员需要查看同意链接并批准你的应用程序。A Global Administrator from your user's tenant needs to view the consent link and approve your application.

    同意链接的形式为:Consent link is of the form:

    https://login.microsoftonline.com/common/oauth2/authorize?prompt=consent&client_id=00000000-0000-0000-0000-000000000000&response_type=code&sso_reload=true
    

    数字 00000000-0000-0000-0000-000000000000 应替换为应用程序 ID。The digits 00000000-0000-0000-0000-000000000000 should be replaced with your Application ID.

    单击同意链接后,使用用户租户的全局管理员登录并许可应用程序。After clicking on the consent link, sign in with the Global Administrator of the user's tenant and consent the application.

    同意图像

    你还需要向用户询问其租户 ID。You'll also need to ask your user for their tenant ID. 租户 ID 是用于获取访问令牌的标识符之一。The tenant ID is one of the identifiers used to acquire access tokens.

  • 完成!Done! 已成功注册应用程序!You've successfully registered an application!
  • 有关令牌获取和验证,请参阅以下示例。See examples below for token acquisition and validation.

获取访问令牌Get an access token

有关 Azure AD 令牌详细信息,请参阅 Azure AD 教程For more information on Azure AD 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.

提示

在下面的示例中,使用用户的租户 ID 测试脚本是否正常工作。In the following examples, use a user's tenant ID to test that the script is working.

使用 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!

$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.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 应用程序 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 user 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"}

验证令牌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're 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();