您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

使用 Active Directory 对 Batch 服务解决方案进行身份验证Authenticate Batch service solutions with Active Directory

Azure Batch 支持通过Azure Active Directory (Azure AD) 进行身份验证。Azure Batch supports authentication with Azure Active Directory (Azure AD). Azure AD 是 Microsoft 提供的基于多租户云的目录和标识管理服务。Azure AD is Microsoft’s multi-tenant cloud based directory and identity management service. Azure 本身使用 Azure AD 对其客户、服务管理员和组织用户进行身份验证。Azure itself uses Azure AD to authenticate its customers, service administrators, and organizational users.

在使用 Azure Batch 对 Azure AD 进行身份验证时,可以通过以下两种方式之一进行身份验证:When using Azure AD authentication with Azure Batch, you can authenticate in one of two ways:

  • 使用集成身份验证对与应用程序交互的用户进行身份验证。By using integrated authentication to authenticate a user that is interacting with the application. 使用集成身份验证的应用程序收集用户的凭据,并使用这些凭据对 Batch 资源访问进行身份验证。An application using integrated authentication gathers a user's credentials and uses those credentials to authenticate access to Batch resources.
  • 使用服务主体对无人参与的应用程序进行身份验证。By using a service principal to authenticate an unattended application. 服务主体定义应用程序的策略和权限,使其能够在运行时访问资源时代表应用程序。A service principal defines the policy and permissions for an application in order to represent the application when accessing resources at runtime.

有关 Azure AD 的详细信息,请阅读 Azure Active Directory 文档To learn more about Azure AD, see the Azure Active Directory Documentation.

身份验证终结点Endpoints for authentication

若要使用 Azure AD 对 Batch 应用程序进行验证,需要在代码中包含一些已知终结点。To authenticate Batch applications with Azure AD, you need to include some well-known endpoints in your code.

Azure AD 终结点Azure AD endpoint

基础 Azure AD 颁发机构终结点是:The base Azure AD authority endpoint is:

https://login.microsoftonline.com/

要使用 Azure AD 进行验证,请将此终结点与租户 ID(即目录 ID)一起使用。To authenticate with Azure AD, you use this endpoint together with the tenant ID (directory ID). 租户 ID 用于标识要用于身份验证的 Azure AD 租户。The tenant ID identifies the Azure AD tenant to use for authentication. 若要检索租户 ID,请按照获取 Azure Active Directory 的租户 ID中概述的步骤进行操作:To retrieve the tenant ID, follow the steps outlined in Get the tenant ID for your Azure Active Directory:

https://login.microsoftonline.com/<tenant-id>

备注

使用服务主体进行验证时,需要特定于租户的终结点。The tenant-specific endpoint is required when you authenticate using a service principal.

使用集成身份验证进行验证时,虽然特定于租户的终结点为可选,但仍推荐。The tenant-specific endpoint is optional when you authenticate using integrated authentication, but recommended. 然而,还可以使用 Azure AD 常用终结点。However, you can also use the Azure AD common endpoint. 未提供特定租户时,该常用终结点可提供泛型凭据收集接口。The common endpoint provides a generic credential gathering interface when a specific tenant is not provided. 常用终结点为 https://login.microsoftonline.com/commonThe common endpoint is https://login.microsoftonline.com/common.

有关 Azure AD 终结点的详细信息, 请参阅Azure AD 的身份验证方案For more information about Azure AD endpoints, see Authentication Scenarios for Azure AD.

Batch 资源终结点Batch resource endpoint

Azure Batch 资源终结点用于获取对 Batch 服务的请求进行身份验证的令牌:Use the Azure Batch resource endpoint to acquire a token for authenticating requests to the Batch service:

https://batch.core.windows.net/

向租户注册应用程序Register your application with a tenant

使用 Azure AD 进行验证的第一步是在 Azure AD 租户中注册应用程序。The first step in using Azure AD to authenticate is registering your application in an Azure AD tenant. 通过注册应用程序,可以从代码中调用 Azure Active Directory 身份验证库 (ADAL)。Registering your application enables you to call the Azure Active Directory Authentication Library (ADAL) from your code. ADAL 提供了一个 API,用于从应用程序中使用 Azure AD 进行身份验证。The ADAL provides an API for authenticating with Azure AD from your application. 无论是计划使用集成身份验证还是服务主体,都必须注册应用程序。Registering your application is required whether you plan to use integrated authentication or a service principal.

注册应用程序时,需要向 Azure AD 提供关于应用程序的信息。When you register your application, you supply information about your application to Azure AD. 然后,Azure AD 将提供一个应用程序 ID(也称为“客户端 ID”),在运行时,可以使用该 ID 将应用程序与 Azure AD 相关联。Azure AD then provides an application ID (also called a client ID) that you use to associate your application with Azure AD at runtime. 若要详细信息应用程序 ID,请参阅 Azure Active Directory 中的应用程序对象和服务主体对象To learn more about the application ID, see Application and service principal objects in Azure Active Directory.

若要注册批处理应用程序, 请遵循将应用程序与 Azure Active Directory 集成中的添加应用程序部分中的步骤。To register your Batch application, follow the steps in the Adding an Application section in Integrating applications with Azure Active Directory. 如果将应用程序注册为本机应用程序,可以为重定向 URI 指定任何有效 URI。If you register your application as a Native Application, you can specify any valid URI for the Redirect URI. 它不需要是实际的终结点。It does not need to be a real endpoint.

注册应用程序后,会看到应用程序 ID:After you've registered your application, you'll see the application ID:

将批处理应用程序注册到 Azure AD

有关使用 Azure AD 注册应用程序的详细信息,请参阅 Azure AD 的身份验证方案For more information about registering an application with Azure AD, see Authentication Scenarios for Azure AD.

获取 Active Directory 的租户 IDGet the tenant ID for your Active Directory

租户 ID 用于标识向应用程序提供身份验证服务的 Azure AD 租户。The tenant ID identifies the Azure AD tenant that provides authentication services to your application. 若要获取租户 ID,请按照以下步骤操作:To get the tenant ID, follow these steps:

  1. 在 Azure 门户中,选择 Active Directory。In the Azure portal, select your Active Directory.
  2. 选择“属性”。Select Properties.
  3. 复制为“目录 ID”提供的 GUID 值。Copy the GUID value provided for the Directory ID. 该值也称为租户 ID。This value is also called the tenant ID.

复制目录 ID

使用集成身份验证Use integrated authentication

若要使用集成身份验证进行验证,需要授予应用程序连接到 Batch 服务 API 的权限。To authenticate with integrated authentication, you need to grant your application permissions to connect to the Batch service API. 此步骤使应用程序可使用 Azure AD 对 Batch 服务 API 的调用进行验证。This step enables your application to authenticate calls to the Batch service API with Azure AD.

注册了应用程序后,请按照 Azure 门户中的以下步骤来向其授予对 Batch 服务的访问权限:Once you've registered your application, follow these steps in the Azure portal to grant it access to the Batch service:

  1. 在 Azure 门户的左侧导航窗格中,选择“所有服务”。In the left-hand navigation pane of the Azure portal, choose All services. 选择“应用注册”。Select App Registrations.

  2. 在应用注册列表中搜索应用程序名称:Search for the name of your application in the list of app registrations:

    搜索应用程序名称

  3. 选择应用程序并选择 " API 权限"。Select the application and select API permissions.

  4. 在 " API 权限" 部分中, 选择 "添加权限"。In the API permissions section, select Add a permission.

  5. 在“选择 API”中,搜索 Batch API。In Select an API, search for the Batch API. 搜索每一条字符串,直到找到此 API:Search for each of these strings until you find the API:

    1. Microsoft Azure BatchMicrosoft Azure Batch
    2. ddbf3205-c6bd-46ae-8127-60eb93363864 是此 Batch API 的 ID。ddbf3205-c6bd-46ae-8127-60eb93363864 is the ID for the Batch API.
  6. 找到批处理 API 后, 选择它, 然后选择 "选择"。Once you find the Batch API, select it and select Select.

  7. 在 "选择权限" 中, 选中 " Access Azure Batch" 服务旁边的复选框, 然后选择 "添加权限"。In Select permissions, select the check box next to Access Azure Batch Service and then select Add permissions.

现在, API 权限部分表明 Azure AD 的应用程序可以访问 Microsoft Graph 和 BATCH 服务 API。The API permissions section now shows that your Azure AD application has access to both Microsoft Graph and the Batch service API. 首次向 Azure AD 注册应用时,系统会自动授予对 Microsoft Graph 的权限。Permissions are granted to Microsoft Graph automatically when you first register your app with Azure AD.

授予 API 权限

使用服务主体Use a service principal

若要对以无人参与方式运行的应用程序进行验证,可以使用服务主体。To authenticate an application that runs unattended, you use a service principal. 注册应用程序后,请按照 Azure 门户中的下列步骤配置服务主体:After you've registered your application, follow these steps in the Azure portal to configure a service principal:

  1. 请求应用程序的机密。Request a secret for your application.
  2. 向应用程序分配基于角色的访问控制 (RBAC)。Assign role-based access control (RBAC) to your application.

为应用程序请求机密Request a secret for your application

当应用程序使用服务主体进行身份验证时, 它会将应用程序 ID 和机密发送到 Azure AD。When your application authenticates with a service principal, it sends both the application ID and a secret to Azure AD. 需要创建并复制要在代码中使用的密钥。You'll need to create and copy the secret key to use from your code.

在 Azure 门户中执行以下步骤:Follow these steps in the Azure portal:

  1. 在 Azure 门户的左侧导航窗格中,选择“所有服务”。In the left-hand navigation pane of the Azure portal, choose All services. 选择“应用注册”。Select App Registrations.

  2. 从应用注册列表中选择应用程序。Select your application from the list of app registrations.

  3. 选择应用程序, 然后选择 "证书" & "机密"。Select the application and then select Certificates & secrets. 在 "客户端密码" 部分中, 选择 "新建客户端密码"。In the Client secrets section, select New client secret.

  4. 若要创建机密, 请输入密钥的说明。To create a secret, enter a description for the secret. 然后选择 "一年"、"2 年" 或 "无到期时间" 的密码有效期。Then select an expirations for the secret of either one year, two years, or no expiration..

  5. 选择 "添加" 以创建并显示密钥。Select Add to create and display the secret. 将密钥值复制到安全位置, 因为在离开页面后将无法再次访问。Copy the secret value to a safe place, as you won't be able to access it again after you leave the page.

    创建密钥

为应用程序分配 RBACAssign RBAC to your application

若要使用服务主体进行身份验证, 需要为应用程序分配 RBAC。To authenticate with a service principal, you need to assign RBAC to your application. 请执行以下步骤:Follow these steps:

  1. 在 Azure 门户中,导航到应用程序使用的 Batch 帐户。In the Azure portal, navigate to the Batch account used by your application.
  2. 在批处理帐户的 "设置" 部分, 选择 "访问控制 (IAM) "。In the Settings section of the Batch account, select Access Control (IAM).
  3. 选择“角色分配”选项卡。Select the Role assignments tab.
  4. 选择“添加角色分配”。Select Add role assignment.
  5. 在“角色”下拉列表中,为应用程序选择参与者或读者角色。From the Role drop-down, choose either the Contributor or Reader role for your application. 有关这些角色的详细信息,请参阅 Azure 门户中基于角色的访问控制入门For more information on these roles, see Get started with Role-Based Access Control in the Azure portal.
  6. 在“选择”字段中,输入应用程序的名称。In the Select field, enter the name of your application. 从列表中选择应用程序, 然后选择 "保存"。Select your application from the list, and then select Save.

现在,应用程序应出现在访问控制设置中,同时已分配有 RBAC 角色。Your application should now appear in your access control settings with an RBAC role assigned.

向应用程序分配 RBAC 角色

获取 Azure Active Directory 的租户 IDGet the tenant ID for your Azure Active Directory

租户 ID 用于标识向应用程序提供身份验证服务的 Azure AD 租户。The tenant ID identifies the Azure AD tenant that provides authentication services to your application. 若要获取租户 ID,请按照以下步骤操作:To get the tenant ID, follow these steps:

  1. 在 Azure 门户中,选择 Active Directory。In the Azure portal, select your Active Directory.
  2. 选择“属性”。Select Properties.
  3. 复制为“目录 ID”提供的 GUID 值。Copy the GUID value provided for the Directory ID. 该值也称为租户 ID。This value is also called the tenant ID.

复制目录 ID

代码示例Code examples

此部分中的代码示例演示如何使用集成身份验证和服务主体通过 Azure AD 进行验证。The code examples in this section show how to authenticate with Azure AD using integrated authentication and with a service principal. 这些代码示例大多使用了 .NET,但概念与其他语言类似。Most of these code examples use .NET, but the concepts are similar for other languages.

备注

Azure AD 身份验证令牌在一小时后过期。An Azure AD authentication token expires after one hour. 使用生存期较长的 BatchClient 对象时,我们建议每次发出请求都从 ADAL 中检索令牌,确保始终获得有效的令牌。When using a long-lived BatchClient object, we recommend that you retrieve a token from ADAL on every request to ensure you always have a valid token.

如果要在 .NET 中实现此目的,可编写一个方法从 Azure AD 中检索令牌,并将该方法作为委派传递给 BatchTokenCredentials 对象。To achieve this in .NET, write a method that retrieves the token from Azure AD and pass that method to a BatchTokenCredentials object as a delegate. 这样,每次批处理服务发出请求都会调用该委派方法,确保提供有效的令牌。The delegate method is called on every request to the Batch service to ensure that a valid token is provided. 默认情况下,ADAL 会缓存令牌,以便只在必要时,才从 Azure AD 中检索新令牌。By default ADAL caches tokens, so a new token is retrieved from Azure AD only when necessary. 有关 Azure AD 中的令牌的详细信息, 请参阅Azure AD 的身份验证方案For more information about tokens in Azure AD, see Authentication Scenarios for Azure AD.

代码示例:将 Azure AD 集成身份验证与 Batch .NET 一起使用Code example: Using Azure AD integrated authentication with Batch .NET

若要在 Batch .NET 中使用集成身份验证进行验证,请参考 Azure Batch .NET 包和 ADAL 包。To authenticate with integrated authentication from Batch .NET, reference the Azure Batch .NET package and the ADAL package.

在代码中包含以下 using 语句:Include the following using statements in your code:

using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Auth;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

在代码中引用 Azure AD 终结点,包括租户 ID。Reference the Azure AD endpoint in your code, including the tenant ID. 若要检索租户 ID,请按照获取 Azure Active Directory 的租户 ID中概述的步骤进行操作:To retrieve the tenant ID, follow the steps outlined in Get the tenant ID for your Azure Active Directory:

private const string AuthorityUri = "https://login.microsoftonline.com/<tenant-id>";

引用 Batch 服务资源终结点:Reference the Batch service resource endpoint:

private const string BatchResourceUri = "https://batch.core.windows.net/";

引用 Batch 帐户:Reference your Batch account:

private const string BatchAccountUrl = "https://myaccount.mylocation.batch.azure.com";

指定应用程序的应用程序 ID(客户端 ID)。Specify the application ID (client ID) for your application. 应用程序 ID 在 Azure 门户中的应用注册中提供:The application ID is available from your app registration in the Azure portal:

private const string ClientId = "<application-id>";

另外,如果已将应用程序指定为本机应用程序,请复制你指定的重定向 URI。Also copy the redirect URI that you specified, if you registered your application as a Native Application. 在代码中指定的重定向 URI 必须与注册应用程序时提供的重定向 URI 相匹配:The redirect URI specified in your code must match the redirect URI that you provided when you registered the application:

private const string RedirectUri = "http://mybatchdatasample";

编写一个回调方法从 Azure AD 获取身份验证令牌。Write a callback method to acquire the authentication token from Azure AD. 此处所示的 GetAuthenticationTokenAsync 回调方法调用 ADAL 对与应用程序交互的用户进行验证。The GetAuthenticationTokenAsync callback method shown here calls ADAL to authenticate a user who is interacting with the application. ADAL 提供的 AcquireTokenAsync 方法提示用户输入其凭据,用户提供凭据后,应用程序可继续工作(除非已有缓存凭据):The AcquireTokenAsync method provided by ADAL prompts the user for their credentials, and the application proceeds once the user provides them (unless it has already cached credentials):

public static async Task<string> GetAuthenticationTokenAsync()
{
    var authContext = new AuthenticationContext(AuthorityUri);

    // Acquire the authentication token from Azure AD.
    var authResult = await authContext.AcquireTokenAsync(BatchResourceUri, 
                                                        ClientId, 
                                                        new Uri(RedirectUri), 
                                                        new PlatformParameters(PromptBehavior.Auto));

    return authResult.AccessToken;
}

构造使用委派作为参数的 BatchTokenCredentials 对象。Construct a BatchTokenCredentials object that takes the delegate as a parameter. 使用这些凭据打开 BatchClient 对象。Use those credentials to open a BatchClient object. 可以使用该 BatchClient 对象针对 Batch 服务执行后续操作:You can use that BatchClient object for subsequent operations against the Batch service:

public static async Task PerformBatchOperations()
{
    Func<Task<string>> tokenProvider = () => GetAuthenticationTokenAsync();

    using (var client = await BatchClient.OpenAsync(new BatchTokenCredentials(BatchAccountUrl, tokenProvider)))
    {
        await client.JobOperations.ListJobs().ToListAsync();
    }
}

代码示例:将 Azure AD 服务主体与 Batch .NET 一起使用Code example: Using an Azure AD service principal with Batch .NET

若要在 Batch .NET 中使用服务主体进行验证,请参考 Azure Batch .NET 包和 ADAL 包。To authenticate with a service principal from Batch .NET, reference the Azure Batch .NET package and the ADAL package.

在代码中包含以下 using 语句:Include the following using statements in your code:

using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Auth;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

在代码中引用 Azure AD 终结点,包括租户 ID。Reference the Azure AD endpoint in your code, including the tenant ID. 使用服务主体时,必须提供特定于租户的终结点。When using a service principal, you must provide a tenant-specific endpoint. 若要检索租户 ID,请按照获取 Azure Active Directory 的租户 ID中概述的步骤进行操作:To retrieve the tenant ID, follow the steps outlined in Get the tenant ID for your Azure Active Directory:

private const string AuthorityUri = "https://login.microsoftonline.com/<tenant-id>";

引用 Batch 服务资源终结点:Reference the Batch service resource endpoint:

private const string BatchResourceUri = "https://batch.core.windows.net/";

引用 Batch 帐户:Reference your Batch account:

private const string BatchAccountUrl = "https://myaccount.mylocation.batch.azure.com";

指定应用程序的应用程序 ID(客户端 ID)。Specify the application ID (client ID) for your application. 应用程序 ID 在 Azure 门户中的应用注册中提供:The application ID is available from your app registration in the Azure portal:

private const string ClientId = "<application-id>";

指定从 Azure 门户复制的密钥:Specify the secret key that you copied from the Azure portal:

private const string ClientKey = "<secret-key>";

编写一个回调方法从 Azure AD 获取身份验证令牌。Write a callback method to acquire the authentication token from Azure AD. 此处显示的 GetAuthenticationTokenAsync 回调方法调用 ADAL 进行无人参与的身份验证:The GetAuthenticationTokenAsync callback method shown here calls ADAL for unattended authentication:

public static async Task<string> GetAuthenticationTokenAsync()
{
    AuthenticationContext authContext = new AuthenticationContext(AuthorityUri);
    AuthenticationResult authResult = await authContext.AcquireTokenAsync(BatchResourceUri, new ClientCredential(ClientId, ClientKey));

    return authResult.AccessToken;
}

构造使用委派作为参数的 BatchTokenCredentials 对象。Construct a BatchTokenCredentials object that takes the delegate as a parameter. 使用这些凭据打开 BatchClient 对象。Use those credentials to open a BatchClient object. 然后,使用该 BatchClient 对象针对 Batch 服务执行后续操作:Then use that BatchClient object for subsequent operations against the Batch service:

public static async Task PerformBatchOperations()
{
    Func<Task<string>> tokenProvider = () => GetAuthenticationTokenAsync();

    using (var client = await BatchClient.OpenAsync(new BatchTokenCredentials(BatchAccountUrl, tokenProvider)))
    {
        await client.JobOperations.ListJobs().ToListAsync();
    }
}

代码示例:将 Azure AD 服务主体与 Batch Python 一起使用Code example: Using an Azure AD service principal with Batch Python

若要在 Batch Python 中使用服务主体进行身份验证,请安装并引用 azure-batchazure-common 模块。To authenticate with a service principal from Batch Python, install and reference the azure-batch and azure-common modules.

from azure.batch import BatchServiceClient
from azure.common.credentials import ServicePrincipalCredentials

使用服务主体时,必须提供租户 ID。When using a service principal, you must provide the tenant ID. 若要检索租户 ID,请按照获取 Azure Active Directory 的租户 ID中概述的步骤进行操作:To retrieve the tenant ID, follow the steps outlined in Get the tenant ID for your Azure Active Directory:

TENANT_ID = "<tenant-id>"

引用 Batch 服务资源终结点:Reference the Batch service resource endpoint:

RESOURCE = "https://batch.core.windows.net/"

引用 Batch 帐户:Reference your Batch account:

BATCH_ACCOUNT_URL = "https://myaccount.mylocation.batch.azure.com"

指定应用程序的应用程序 ID(客户端 ID)。Specify the application ID (client ID) for your application. 应用程序 ID 在 Azure 门户中的应用注册中提供:The application ID is available from your app registration in the Azure portal:

CLIENT_ID = "<application-id>"

指定从 Azure 门户复制的密钥:Specify the secret key that you copied from the Azure portal:

SECRET = "<secret-key>"

创建一个 ServicePrincipalCredentials 对象:Create a ServicePrincipalCredentials object:

credentials = ServicePrincipalCredentials(
    client_id=CLIENT_ID,
    secret=SECRET,
    tenant=TENANT_ID,
    resource=RESOURCE
)

使用服务主体凭据打开一个 BatchServiceClient 对象。Use the service principal credentials to open a BatchServiceClient object. 然后,使用该 BatchServiceClient 对象针对 Batch 服务执行后续操作。Then use that BatchServiceClient object for subsequent operations against the Batch service.

    batch_client = BatchServiceClient(
    credentials,
    base_url=BATCH_ACCOUNT_URL
)

后续步骤Next steps