您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.
快速入门:使用应用的标识获取令牌并从 Java 控制台应用中调用 Microsoft Graph APIQuickstart: Acquire a token and call Microsoft Graph API from a Java console app using app's identity
01/22/2021
本文内容
在本快速入门中,你将下载并运行一个代码示例,该示例演示 Java 应用程序如何使用应用的标识获取访问令牌来调用 Microsoft Graph API 并在目录中显示用户列表。In this quickstart, you download and run a code sample that demonstrates how a Java application can get an access token using the app's identity to call the Microsoft Graph API and display a list of users in the directory. 代码示例演示无人参与的作业或 Windows 服务如何使用应用程序标识而不是用户标识运行。The code sample demonstrates how an unattended job or Windows service can run with an application identity, instead of a user's identity.
先决条件Prerequisites
若要运行此示例,需要:To run this sample, you need:
注册并下载快速入门应用Register and download your quickstart app
可以使用两个选项来启动快速入门应用程序:“快速”(下面的选项 1)和“手动”(选项 2)You have two options to start your quickstart application: Express (Option 1 below), and Manual (Option 2)
选项 1:注册并自动配置应用,然后下载代码示例Option 1: Register and auto configure your app and then download your code sample
输入应用程序的名称并选择“注册”。Enter a name for your application and select Register.
遵照说明下载内容,并只需单击一下自动配置新应用程序。Follow the instructions to download and automatically configure your new application with just one click.
选项 2:注册并手动配置应用程序和代码示例Option 2: Register and manually configure your application and code sample
步骤 1:注册应用程序Step 1: Register your application
若要手动注册应用程序并将应用的注册信息添加到解决方案,请执行以下步骤:To register your application and add the app's registration information to your solution manually, follow these steps:
如果有权访问多个租户,请使用顶部菜单中的“目录 + 订阅”筛选器
,选择要在其中注册应用程序的租户。
搜索并选择“Azure Active Directory” 。Search for and select Azure Active Directory.
在“管理”下,选择“应用注册” > “新建注册” 。Under Manage, select App registrations > New registration.
输入应用程序的名称(例如 Daemon-console)。Enter a Name for your application, for example Daemon-console. 应用的用户可能会看到此名称,你稍后可对其进行更改。Users of your app might see this name, and you can change it later.
选择“注册” 。Select Register.
在“管理”下,选择“证书和机密” 。Under Manage, select Certificates & secrets.
在“客户端机密”下,选择“新建客户端机密”,输入名称,然后选择“添加” 。Under Client secrets, select New client secret, enter a name, and then select Add. 将机密值记录在安全的位置,以供在后面的步骤中使用。Record the secret value in a safe location for use in a later step.
在“管理”下,选择“API 权限” > “添加权限” 。Under Manage, select API Permissions > Add a permission. 选择“Microsoft Graph”。Select Microsoft Graph.
选择“应用程序权限”。Select Application permissions.
在“用户”节点下选择“User.Read.All”,然后选择“添加权限” 。Under User node, select User.Read.All, then select Add permissions.
下载并配置快速入门应用Download and configure the quickstart app
步骤 1:在 Azure 门户中配置应用程序Step 1: Configure the application in Azure portal
为使本快速入门的代码示例正常运行,需创建客户端机密,并添加 Graph API 的 User.Read.All 应用程序权限。For the code sample for this quickstart to work, you need to create a client secret, and add Graph API's User.Read.All application permission.
应用程序已使用这些属性进行配置。
Your application is configured with these attributes.
步骤 2:下载 Java 项目Step 2: Download the Java project
备注
Enter_the_Supported_Account_Info_Here
步骤 3:配置 Java 项目Step 3: Configure the Java project
将 zip 文件提取到靠近磁盘根目录的本地文件夹,例如 C:\Azure-Samples。Extract the zip file to a local folder close to the root of the disk, for example, C:\Azure-Samples.
导航到子文件夹 msal-client-credential-secret。Navigate to the sub folder msal-client-credential-secret.
编辑 src\main\resources\application.properties,并将字段 AUTHORITY、CLIENT_ID 和 SECRET 的值替换为以下代码片段:Edit src\main\resources\application.properties and replace the values of the fields AUTHORITY, CLIENT_ID, and SECRET with the following snippet:
AUTHORITY=https://login.microsoftonline.com/Enter_the_Tenant_Id_Here/
CLIENT_ID=Enter_the_Application_Id_Here
SECRET=Enter_the_Client_Secret_Here
其中:Where:
Enter_the_Application_Id_Here - 是已注册应用程序的 应用程序(客户端)ID。Enter_the_Application_Id_Here - is the Application (client) ID for the application you registered.
Enter_the_Tenant_Id_Here - 将此值替换为租户 ID 或租户名称(例如 contoso.microsoft.com) 。Enter_the_Tenant_Id_Here - replace this value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
Enter_the_Client_Secret_Here - 将此值替换为在步骤 1 中创建的客户端机密。Enter_the_Client_Secret_Here - replace this value with the client secret created on step 1.
提示
若要查找“应用程序(客户端) ID”、“目录(租户) ID”的值,请转到 Azure 门户中应用的“概览”页。To find the values of Application (client) ID, Directory (tenant) ID, go to the app's Overview page in the Azure portal. 若要生成新密钥,请转到“证书和机密”页。To generate a new key, go to Certificates & secrets page.
步骤 3:管理员同意Step 3: Admin consent
步骤 4:管理员同意Step 4: Admin consent
如果尝试在此时运行应用程序,则会收到“HTTP 403 - 禁止访问”错误:Insufficient privileges to complete the operation。If you try to run the application at this point, you'll receive HTTP 403 - Forbidden error: Insufficient privileges to complete the operation. 之所以出现这种错误,是因为任何仅限应用的权限都需要管理员许可:目录的全局管理员必须为应用程序授予许可。This error happens because any app-only permission requires Admin consent: a global administrator of your directory must give consent to your application. 根据自己的角色选择下面的一个选项:Select one of the options below depending on your role:
全局租户管理员Global tenant administrator
如果你是全局租户管理员,请在 Azure 门户中转到“应用注册”中的“API 权限”页面,选择“为 {租户名称} 授予管理员许可”(其中,{租户名称} 是目录的名称) 。If you are a global tenant administrator, go to API Permissions page in App registrations in the Azure portal and select Grant admin consent for {Tenant Name} (Where {Tenant Name} is the name of your directory).
如果你是全局管理员,请转到“API 权限”页面,选择“为 Enter_the_Tenant_Name_Here 授予管理员许可” 。If you are a global administrator, go to API Permissions page select Grant admin consent for Enter_the_Tenant_Name_Here.
标准用户Standard user
如果你是租户的标准用户,则需请求全局管理员为你的应用程序授予管理员许可。If you're a standard user of your tenant, then you need to ask a global administrator to grant admin consent for your application. 为此,请将以下 URL 提供给管理员:To do this, give the following URL to your administrator:
https://login.microsoftonline.com/Enter_the_Tenant_Id_Here/adminconsent?client_id=Enter_the_Application_Id_Here
其中:Where:
Enter_the_Tenant_Id_Here - 将此值替换为 租户 ID 或 租户名称(例如 contoso.microsoft.com)Enter_the_Tenant_Id_Here - replace this value with the Tenant Id or Tenant name (for example, contoso.microsoft.com)
Enter_the_Application_Id_Here - 是已注册应用程序的 应用程序(客户端)ID。Enter_the_Application_Id_Here - is the Application (client) ID for the application you registered.
步骤 4:运行应用程序Step 4: Run the application
步骤 5:运行应用程序Step 5: Run the application
可通过从 IDE 中运行 ClientCredentialGrant.java 的主方法,直接测试示例。You can test the sample directly by running the main method of ClientCredentialGrant.java from your IDE.
从 shell 或命令行:From your shell or command line:
$ mvn clean compile assembly:single
这将在 /targets 目录中生成一个 msal-client-credential-secret-1.0.0.jar 文件。This will generate a msal-client-credential-secret-1.0.0.jar file in your /targets directory. 使用 Java 可执行文件运行此内容,如下所示:Run this using your Java executable like below:
$ java -jar msal-client-credential-secret-1.0.0.jar
运行后,应用程序应显示配置的租户中的用户列表。After running, the application should display the list of users in the configured tenant.
重要
本快速入门应用程序使用客户端机密将自己标识为机密客户端。This quickstart application uses a client secret to identify itself as confidential client. 由于客户端机密是以纯文本形式添加到项目文件的,因此为了安全起见,建议在考虑将应用程序用作生产应用程序之前,使用证书来代替客户端机密。Because the client secret is added as a plain-text to your project files, for security reasons, it is recommended that you use a certificate instead of a client secret before considering the application as production application. 若要详细了解如何使用证书,请查看有关此示例的这些说明,它们位于同一 GitHub 存储库中,但在另一个文件夹“msal-client-credential-certificate”中。For more information on how to use a certificate, see these instructions in the same GitHub repository for this sample, but in the second folder msal-client-credential-certificate.
详细信息More information
MSAL JavaMSAL Java
MSAL Java 是一个用于登录用户和请求令牌的库,此类令牌用于访问受 Microsoft 标识平台保护的 API。MSAL Java is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. 如前所述,本快速入门请求令牌的方法是使用应用程序自身的标识而不是委托的权限。As described, this quickstart requests tokens by using the application own identity instead of delegated permissions. 在此示例中使用的身份验证流称为客户端凭据 oauth 流。The authentication flow used in this case is known as 若要详细了解如何搭配使用 MSAL Java 和守护程序应用,请参阅本文。For more information on how to use MSAL Java with daemon apps, see this article.
可以使用 Maven 或 Gradle 将 MSAL4J 添加到应用程序,以通过对应用程序的 pom.xml (Maven) 或 build.gradle (Gradle) 文件进行以下更改来管理依赖项。Add MSAL4J to your application by using Maven or Gradle to manage your dependencies by making the following changes to the application's pom.xml (Maven) or build.gradle (Gradle) file.
在 pom.xml 中:In pom.xml:
com.microsoft.azure
msal4j
1.0.0
在 build.gradle 中:In build.gradle:
compile group: 'com.microsoft.azure', name: 'msal4j', version: '1.0.0'
MSAL 初始化MSAL initialization
通过将以下代码添加到要在其中使用 MSAL4J 的文件的顶部,来添加对 MSAL for Java 的引用:Add a reference to MSAL for Java by adding the following code to the top of the file where you will be using MSAL4J:
import com.microsoft.aad.msal4j.*;
然后,使用以下代码对 MSAL 进行初始化:Then, initialize MSAL using the following code:
IClientCredential credential = ClientCredentialFactory.createFromSecret(CLIENT_SECRET);
ConfidentialClientApplication cca =
ConfidentialClientApplication
.builder(CLIENT_ID, credential)
.authority(AUTHORITY)
.build();
其中:Where:
说明Description
CLIENT_SECRET
是在 Azure 门户中为应用程序创建的客户端机密。Is the client secret created for the application in Azure Portal.
CLIENT_ID
是在 Azure 门户中注册的应用程序的 应用程序(客户端) ID。Is the Application (client) ID for the application registered in the Azure portal. 可以在 Azure 门户的应用的“概览”页中找到此值。You can find this value in the app's Overview page in the Azure portal.
AUTHORITY
用户要进行身份验证的 STS 终结点。The STS endpoint for user to authenticate. 对于公有云,通常为 https://login.microsoftonline.com/{tenant},其中 {tenant} 是租户名称或租户 ID。Usually https://login.microsoftonline.com/{tenant} for public cloud, where {tenant} is the name of your tenant or your tenant Id.
请求令牌Requesting tokens
若要通过应用的标识来请求令牌,请使用 acquireToken 方法:To request a token using app's identity, use acquireToken method:
IAuthenticationResult result;
try {
SilentParameters silentParameters =
SilentParameters
.builder(SCOPE)
.build();
// try to acquire token silently. This call will fail since the token cache does not
// have a token for the application you are requesting an access token for
result = cca.acquireTokenSilently(silentParameters).join();
} catch (Exception ex) {
if (ex.getCause() instanceof MsalException) {
ClientCredentialParameters parameters =
ClientCredentialParameters
.builder(SCOPE)
.build();
// Try to acquire a token. If successful, you should see
// the token information printed out to console
result = cca.acquireToken(parameters).join();
} else {
// Handle other exceptions accordingly
throw ex;
}
}
return result;
其中:Where:
说明Description
SCOPE
包含请求的范围。Contains the scopes requested. 对于机密客户端,这应该使用与 {Application ID URI}/.default 类似的格式,指示所请求的范围是在 Azure 门户的应用对象集中静态定义的范围(就 Microsoft Graph 来说,{Application ID URI} 指向 https://graph.microsoft.com)。For confidential clients, this should use the format similar to {Application ID URI}/.default to indicate that the scopes being requested are the ones statically defined in the app object set in the Azure portal (for Microsoft Graph, {Application ID URI} points to https://graph.microsoft.com). 对于自定义 Web API,{Application ID URI} 是在 Azure 门户的“应用注册”的“公开 API”部分中定义的 。For custom web APIs, {Application ID URI} is defined under the Expose an API section in App registrations in the Azure Portal.
帮助和支持Help and support
如果需要帮助、需要报告问题,或者需要详细了解支持选项,请参阅面向开发人员的帮助和支持。If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.
后续步骤Next steps
若要详细了解守护程序应用程序,请参阅方案登陆页面。To learn more about daemon applications, see the scenario landing page.