快速入门:向 Java Web 应用添加 Microsoft 登录功能Quickstart: Add sign-in with Microsoft to a Java web app

本快速入门介绍如何将 Java Web 应用与 Microsoft 标识平台集成。In this quickstart, you'll learn how to integrate a Java web application with the Microsoft identity platform. 应用会将用户登录,获取用于调用 Microsoft Graph API 的访问令牌,并针对 Microsoft Graph API 发出请求。Your app will sign in a user, get an access token to call the Microsoft Graph API, and make a request to the Microsoft Graph API.

完成本快速入门后,该应用程序将接受任何公司或组织中使用 Azure Active Directory 的工作或学校帐户进行登录。When you've completed this quickstart, your application will accept sign-ins of work or school accounts from any company or organization that uses Azure Active Directory. (有关说明,请参阅示例工作原理。)(See How the sample works for an illustration.)


若要运行此示例,需要:To run this sample you will need:

注册并下载快速入门应用Register and download your quickstart app

可以使用两个选项来启动快速入门应用程序:“快速”(选项 1)和“手动”(选项 2)You have two options to start your quickstart application: express (Option 1), or manual (Option 2)

选项 1:注册并自动配置应用,然后下载代码示例Option 1: Register and auto configure your app and then download your code sample

  1. 转到 Azure 门户 - 应用注册快速入门体验。Go to the Azure portal - App registrations quickstart experience.
  2. 输入应用程序的名称并选择“注册”。Enter a name for your application and select Register.
  3. 按照门户快速入门体验中的说明下载自动配置的应用程序代码。Follow the instructions in the portal's quickstart experience to download the automatically configured application code.

选项 2:注册并手动配置应用程序和代码示例Option 2: Register and manually configure your application and code sample

步骤 1:注册应用程序Step 1: Register your application

若要注册应用程序并将应用的注册信息手动添加到应用程序,请执行以下步骤:To register your application and manually add the app's registration information to your application, follow these steps:

  1. 使用工作或学校帐户登录到 Azure 门户Sign in to the Azure portal using a work or school account.

  2. 如果你的帐户有权访问多个租户,请在右上角选择该帐户,并将门户会话设置为所需的 Azure AD 租户。If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the desired Azure AD tenant.

  3. 导航到面向开发人员的 Microsoft 标识平台的应用注册页。Navigate to the Microsoft identity platform for developers App registrations page.

  4. 选择“新注册”。Select New registration.

  5. “注册应用程序”页出现后,请输入应用程序的注册信息:When the Register an application page appears, enter your application's registration information:

    • 在“名称”部分输入一个会显示给应用用户的有意义的应用程序名称,例如 java-webappIn the Name section, enter a meaningful application name that will be displayed to users of the app, for example java-webapp.
    • 选择“注册”。Select Register.
  6. 在“概述”页上,找到应用程序的“应用程序(客户端) ID”和“目录(租户) ID”值。On the Overview page, find the Application (client) ID and the Directory (tenant) ID values of the application. 复制这些值,供以后使用。Copy these values for later.

  7. 从菜单选择“身份验证”,然后添加以下信息:Select the Authentication from the menu, and then add the following information:

    • 添加“Web”平台配置。Add the Web platform configuration. 将这些 https://localhost:8443/msal4jsample/secure/aadhttps://localhost:8443/msal4jsample/graph/me 添加为“重定向 URI”。Add these https://localhost:8443/msal4jsample/secure/aad and https://localhost:8443/msal4jsample/graph/me as Redirect URIs..
    • 选择“保存”。Select Save.
  8. 在菜单中选择“证书和密码”,然后在“客户端密码”部分中单击“新建客户端密码”: Select the Certificates & secrets from the menu and in the Client secrets section, click on New client secret:

    • 键入(实例应用密码的)密钥说明。Type a key description (for instance app secret).
    • 选择密钥持续时间“1 年”。Select a key duration In 1 year.
    • 选择“添加”时,将显示密钥值。The key value will display when you select Add.
    • 复制密钥的值供以后使用。Copy the value of the key for later. 该密钥值将不会再次显示,也无法通过其他任何方式检索,因此,该值在 Azure 门户中显示时,请立即记下来。This key value will not be displayed again, nor retrievable by any other means, so record it as soon as it is visible from the Azure portal.

步骤 1:在 Azure 门户中配置应用程序Step 1: Configure your application in the Azure portal

若要正常运行本快速入门中的代码示例,需要:For the code sample for this quickstart to work, you need to:

  1. 添加 https://localhost:8443/msal4jsample/secure/aadhttps://localhost:8443/msal4jsample/graph/me 作为回复 URLAdd reply URLs as https://localhost:8443/msal4jsample/secure/aad and https://localhost:8443/msal4jsample/graph/me
  2. 创建客户端机密。Create a Client Secret.

已配置 应用程序已使用这些属性进行配置。Already configured Your application is configured with these attributes.

步骤 2:下载代码示例Step 2: Download the code sample

下载项目并将 zip 文件解压缩到更靠近根文件夹的本地文件夹(例如,C:\Azure-SamplesDownload the project and extract the zip file to a local folder closer to the root folder - for example, C:\Azure-Samples

若要将 https 与 localhost 一起使用,请填写 server.ssl.key 属性。To use https with localhost, fill in the server.ssl.key properties. 若要生成自签名证书,请使用 keytool 实用工具(包含在 JRE 中)。To generate a self-signed certificate, use the keytool utility (included in JRE).

 keytool -genkeypair -alias testCert -keyalg RSA -storetype PKCS12 -keystore keystore.p12 -storepass password


将生成的 keystore 文件放在“resources”文件夹中。Put the generated keystore file in the "resources" folder.



步骤 3:配置代码示例Step 3: Configure the code sample

  1. 将 zip 文件解压缩到某个本地文件夹。Extract the zip file to a local folder.

  2. 如果使用集成开发环境,请在偏好的 IDE 中打开示例(可选)。If you use an integrated development environment, open the sample in your favorite IDE (optional).

  3. 打开可在 src/main/resources/ 文件夹中找到的 application.properties 文件,将字段“aad.clientId”、“aad.authority”和“aad.secretKey”的值替换为相应的“应用程序 ID”、“租户 ID”和“客户端密码”值,如下所示 :Open the application.properties file, which can be found in src/main/resources/ folder and replace the value of the fields aad.clientId, aad.authority and aad.secretKey with the respective values of Application Id, Tenant Id and Client Secret as the following:



  • Enter_the_Application_Id_here - 是已注册应用程序的应用程序 ID。Enter_the_Application_Id_here - is the Application Id for the application you registered.
  • Enter_the_Client_Secret_Here - 是你在“证书和机密”中为注册的应用程序创建的客户端密码Enter_the_Client_Secret_Here - is the Client Secret you created in Certificates & Secrets for the application you registered.
  • Enter_the_Tenant_Info_Here - 是注册的应用程序的目录(租户)ID 值。Enter_the_Tenant_Info_Here - is the Directory (tenant) ID value of the application you registered.
  1. 若要将 https 与 localhost 一起使用,请填写 server.ssl.key 属性。To use https with localhost, fill in the server.ssl.key properties. 若要生成自签名证书,请使用 keytool 实用工具(包含在 JRE 中)。To generate a self-signed certificate, use the keytool utility (included in JRE).
 keytool -genkeypair -alias testCert -keyalg RSA -storetype PKCS12 -keystore keystore.p12 -storepass password


将生成的 keystore 文件放在“resources”文件夹中。Put the generated keystore file in the "resources" folder.

步骤 3:运行代码示例Step 3: Run the code sample

步骤 4:运行代码示例Step 4: Run the code sample

若要运行该项目,可以:To run the project, you can either:

使用嵌入的 spring boot 服务器直接从 IDE 中运行它,或使用 maven 将其打包到 WAR 文件,然后将其部署到 J2EE 容器解决方案,如 Apache TomcatRun it directly from your IDE by using the embedded spring boot server or package it to a WAR file using maven and deploy it to a J2EE container solution such as Apache Tomcat.

从 IDE 运行Running from IDE

如果从 IDE 运行 Web 应用程序,请单击“运行”,然后导航到项目的主页。If you are running the web application from an IDE, click on run, then navigate to the home page of the project. 对于本示例,标准主页 URL 为 https://localhost:8443For this sample, the standard home page URL is https://localhost:8443

  1. 在前面的页面上,选择“登录”按钮以重定向到 Azure Active Directory 并提示用户输入其凭据。On the front page, select the Login button to redirect to Azure Active Directory and prompt the user for their credentials.

  2. 用户通过身份验证后,会重定向到 https://localhost:8443/msal4jsample/secure/aad。After the user is authenticated, they are redirected to https://localhost:8443/msal4jsample/secure/aad. 他们现在已登录,页面将显示有关已登录帐户的信息。They are now signed in, and the page will show information about the signed-in account. 示例 UI 包含以下按钮:The sample UI has the following buttons:

    • 注销:从应用程序中注销当前用户,并将其重定向到主页。Sign Out: Signs the current user out of the application and redirects them to the home page.
    • 显示用户信息:获取 Microsoft Graph 的令牌,并使用包含该令牌的请求调用 Microsoft Graph,这将返回有关已登录用户的基本信息。Show User Info: Acquires a token for Microsoft Graph and calls Microsoft Graph with a request containing the token, which returns basic information about the signed-in user.
从 Tomcat 运行Running from Tomcat

若要将 Web 示例部署到 Tomcat,需要对源代码进行一些更改。If you would like to deploy the web sample to Tomcat, you will need to make a couple of changes to the source code.

  1. 打开 ms-identity-java-webapp/pom.xmlOpen ms-identity-java-webapp/pom.xml

    • <name>msal-web-sample</name> 下添加 <packaging>war</packaging>Under <name>msal-web-sample</name> add <packaging>war</packaging>
  2. 打开 ms-identity-java-webapp/src/main/java/com.microsoft.azure.msalwebsample/MsalWebSampleApplicationOpen ms-identity-java-webapp/src/main/java/com.microsoft.azure.msalwebsample/MsalWebSampleApplication

    • 删除所有源代码,将其替换为以下内容:Delete all source code and replace with the following:
     package com.microsoft.azure.msalwebsample;
     import org.springframework.boot.SpringApplication;
     import org.springframework.boot.autoconfigure.SpringBootApplication;
     import org.springframework.boot.builder.SpringApplicationBuilder;
     import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
     public class MsalWebSampleApplication extends SpringBootServletInitializer {
      public static void main(String[] args) {
       SpringApplication.run(MsalWebSampleApplication.class, args);
      protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
       return builder.sources(MsalWebSampleApplication.class);
  3. Tomcat 的默认 HTTP 端口为 8080,但需通过端口 8443 进行 HTTPS 连接。Tomcat's default HTTP port is 8080, though an HTTPS connection over port 8443 is needed. 对此进行配置:To configure this:

    • 转到 tomcat/conf/server.xmlGo to tomcat/conf/server.xml
    • 搜索 <connector> 标记,并将现有连接器替换为:Search for the <connector> tag, and replace the existing connector with:
               port="8443" maxThreads="200"
               scheme="https" secure="true" SSLEnabled="true"
               keystoreFile="C:/Path/To/Keystore/File/keystore.p12" keystorePass="KeystorePassword"
               clientAuth="false" sslProtocol="TLS"/>
  4. 打开命令提示符,转到此示例的根文件夹(pom.xml 位于其中),然后运行 mvn package 以生成项目Open a command prompt, go to the root folder of this sample (where the pom.xml file is located), and run mvn package to build the project

    • 这会在 /targets 目录中生成一个 msal-web-sample-0.1.0.war 文件。This will generate a msal-web-sample-0.1.0.war file in your /targets directory.
    • 将此文件重命名为 msal4jsample.warRename this file to msal4jsample.war
    • 使用 Tomcat 或任何其他 J2EE 容器解决方案部署此 war 文件。Deploy this war file using Tomcat or any other J2EE container solution.
      • 若要部署,请将 msal4jsample.war 文件复制到 Tomcat 安装中的 /webapps/ 目录,然后启动 Tomcat 服务器。To deploy, copy the msal4jsample.war file to the /webapps/ directory in your Tomcat installation, and then start the Tomcat server.
  5. 部署后,在浏览器中转到 https://localhost:8443/msal4jsampleOnce deployed, go to https://localhost:8443/msal4jsample in your browser


本快速入门应用程序使用客户端机密将自己标识为机密客户端。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. 有关如何使用证书的详细信息,请参阅用于应用程序身份验证的证书凭据For more information on how to use a certificate, see Certificate credentials for application authentication.

详细信息More information

示例工作原理How the sample works


获取 MSALGetting MSAL

MSAL for Java (MSAL4J) 是一个 Java 库,用于用户登录和请求令牌,此类令牌用于访问受 Microsoft 标识平台保护的 API。MSAL for Java (MSAL4J) is the Java library used to sign in users and request tokens used to access an API protected by the Microsoft identity Platform.

可以使用 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:


在 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.*;

后续步骤Next Steps

了解有关权限和许可的详细信息:Learn more about permissions and consent:

若要详细了解此方案的授权流,请查看 Oauth 2.0 授权代码流:To know more about the auth flow for this scenario, see the Oauth 2.0 authorization code flow:

帮助和支持Help and support

如果需要帮助、需要报告问题,或者需要详细了解支持选项,请参阅面向开发人员的帮助和支持If you need help, want to report an issue, or would like to learn about your support options, see Help and support for developers.