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

在本快速入门中,你将下载并运行一个代码示例,该示例演示 Java Web 应用程序如何让用户登录并调用 Microsoft Graph API。In this quickstart, you download and run a code sample that demonstrates how a Java web application can sign in users and call the Microsoft Graph API. 任何 Azure Active Directory (Azure AD) 组织的用户都可以登录到应用程序。Users from any Azure Active Directory (Azure AD) organization can sign in to the application.

有关概述,请参阅示例工作原理关系图For an overview, see the diagram of how the sample works.

先决条件Prerequisites

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

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

可以通过两种方式来启动快速入门应用程序:“快速”(选项 1)和“手动”(选项 2)。There are two ways to start your quickstart application: express (option 1) and manual (option 2).

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

  1. 转到 Azure 门户 > 注册应用程序快速入门体验。Go to the Azure portal > Registration an application quickstart experience.
  2. 输入应用程序的名称并选择“注册”。Enter a name for your application, and then 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 it, follow these steps:

  1. 登录到 Azure 门户Sign in to the Azure portal.
  2. 如果有权访问多个租户,请使用顶部菜单中的“目录 + 订阅”筛选器 ,选择要在其中注册应用程序的租户。
  3. 搜索并选择“Azure Active Directory” 。Search for and select Azure Active Directory.
  4. 在“管理”下,选择“应用注册”。Under Manage, select App registrations.
  5. 选择“新注册”。Select New registration.
  6. 输入应用程序的名称(例如 java-webapp) 。Enter a Name for your application, for example java-webapp. 应用的用户可能会看到此名称。Users of your app might see this name. 稍后可对其进行更改。You can change it later.
  7. 选择“注册”。Select Register.
  8. 在“概述”页面上,记下“应用程序(客户端) ID”和“目录(租户) ID” 。On the Overview page, note the Application (client) ID and the Directory (tenant) ID. 在后面的步骤中会用到这些值。You'll need these values later.
  9. 在“管理”下,选择“身份验证”。 Under Manage, select Authentication.
  10. 选择“添加平台” > “Web” 。Select Add a platform > Web.
  11. 在“重定向 URI”部分中,输入 https://localhost:8443/msal4jsample/secure/aadIn the Redirect URIs section, enter https://localhost:8443/msal4jsample/secure/aad.
  12. 选择“配置” 。Select Configure.
  13. 在“Web”部分的“重定向 URI”下,输入 https://localhost:8443/msal4jsample/graph/me 作为第二个重定向 URI 。In the Web section, under Redirect URIs, enter https://localhost:8443/msal4jsample/graph/me as a second redirect URI.
  14. 在“管理”下,选择“证书和机密”。 Under Manage, select Certificates & secrets. 在“客户端密码”部分中,选择“新建客户端密码” 。In the Client secrets section, select New client secret.
  15. 输入密钥说明(例如应用机密),保留默认的到期日期,然后选择“添加”。Enter a key description (for example, app secret), leave the default expiration, and select Add.
  16. 记下客户端密码的值。Note the Value of the client secret. 稍后需要用到此信息。You'll need it later.

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

若要在此快速入门中使用代码示例,你需要:To use the code sample in this quickstart, you need to:

  1. 添加回复 URL https://localhost:8443/msal4jsample/secure/aadhttps://localhost:8443/msal4jsample/graph/meAdd reply URLs 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 文件解压缩到驱动器根目录附近的文件夹中。Download the project and extract the .zip file into a folder near the root of your drive. 例如,C:\Azure-Samples。For example, C:\Azure-Samples.

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

下面是一个示例:Here's an example:

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

 server.ssl.key-store-type=PKCS12
 server.ssl.key-store=classpath:keystore.p12
 server.ssl.key-store-password=password
 server.ssl.key-alias=testCert

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

备注

Enter_the_Supported_Account_Info_Here

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

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

  2. 可选。Optional. 如果使用集成开发环境,请在该环境中打开示例。If you use an integrated development environment, open the sample in that environment.

  3. 打开 application.properties 文件。Open the application.properties file. 可以在 src/main/resources/ 文件夹中找到它。You can find it in the src/main/resources/ folder. 将字段 aad.clientIdaad.authorityaad.secretKey 中的值分别替换为应用程序 ID、租户 ID 和客户端密码值。Replace the values in the fields aad.clientId, aad.authority, and aad.secretKey with the application ID, tenant ID, and client secret values, respectively. 下面是结果的大致形式:Here's what it should look like:

    aad.clientId=Enter_the_Application_Id_here
    aad.authority=https://login.partner.microsoftonline.cn/Enter_the_Tenant_Info_Here/
    aad.secretKey=Enter_the_Client_Secret_Here
    aad.redirectUriSignin=https://localhost:8443/msal4jsample/secure/aad
    aad.redirectUriGraph=https://localhost:8443/msal4jsample/graph/me
    aad.msGraphEndpointHost="https://microsoftgraph.chinacloudapi.cn/"
    

    在前面的代码中:In the previous code:

    • 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.
  4. 若要将 HTTPS 与 localhost 一起使用,请提供 server.ssl.key 属性。To use HTTPS with localhost, provide the server.ssl.key properties. 若要生成自签名证书,请使用 keytool 实用工具(包含在 JRE 中)。To generate a self-signed certificate, use the keytool utility (included in JRE).

    下面是一个示例:Here's an example:

     keytool -genkeypair -alias testCert -keyalg RSA -storetype PKCS12 -keystore keystore.p12 -storepass password
    
     server.ssl.key-store-type=PKCS12
     server.ssl.key-store=classpath:keystore.p12
     server.ssl.key-store-password=password
     server.ssl.key-alias=testCert
    
  5. 将生成的 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, take one of these steps:

  • 使用嵌入式 Spring Boot 服务器直接从 IDE 运行它。Run it directly from your IDE by using the embedded Spring Boot server.
  • 使用 Maven 将其打包为 WAR 文件,然后将其部署到 J2EE 容器解决方案,如 Apache TomcatPackage it to a WAR file by using Maven, and then deploy it to a J2EE container solution like Apache Tomcat.
从 IDE 中运行项目Running the project from an IDE

若要从 IDE 运行 Web 应用,请选择“运行”,然后转到项目的主页。To run the web application from an IDE, select run, and then go to the home page of the project. 对于本示例,标准主页 URL 为 https://localhost:8443 。For 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 users to Azure Active Directory and prompt them for credentials.

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

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

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

  1. 打开 ms-identity-java-webapp/pom.xml。Open 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/MsalWebSampleApplication。Open ms-identity-java-webapp/src/main/java/com.microsoft.azure.msalwebsample/MsalWebSampleApplication.

    • 删除所有源代码并用以下代码替换:Delete all source code and replace it with this code:

       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;
      
       @SpringBootApplication
       public class MsalWebSampleApplication extends SpringBootServletInitializer {
      
        public static void main(String[] args) {
         SpringApplication.run(MsalWebSampleApplication.class, args);
        }
      
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
         return builder.sources(MsalWebSampleApplication.class);
        }
       }
      
  3. Tomcat 的默认 HTTP 端口是 8080,但需要通过端口 8443 建立 HTTPS 连接。Tomcat's default HTTP port is 8080, but you need an HTTPS connection over port 8443. 配置此设置:To configure this setting:

    • 转到 tomcat/conf/server.xml。Go to tomcat/conf/server.xml.

    • 搜索 <connector> 标记,并用此连接器替换现有连接器:Search for the <connector> tag, and replace the existing connector with this connector:

      <Connector
               protocol="org.apache.coyote.http11.Http11NioProtocol"
               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. 打开命令提示符窗口。Open a Command Prompt window. 转到此示例的根文件夹(pom.xml 位于其中),然后运行 mvn package 以生成项目。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 command will generate a msal-web-sample-0.1.0.war file in your /targets directory.
    • 将此文件重命名为 msal4jsample.war。Rename this file to msal4jsample.war.
    • 使用 Tomcat 或任何其他 J2EE 容器解决方案部署 WAR 文件。Deploy the WAR file by using Tomcat or any other J2EE container solution.
      • 若要部署 msal4jsample.war 文件,请将其复制到 Tomcat 安装中的 /webapps/ 目录,然后启动 Tomcat 服务器。To deploy the msal4jsample.war file, copy it to the /webapps/ directory in your Tomcat installation, and then start the Tomcat server.
  5. 部署完文件后,使用浏览器转到 https://localhost:8443/msal4jsample 。After the file is deployed, go to https://localhost:8443/msal4jsample by using a browser.

重要

本快速入门应用程序使用客户端机密将自己标识为机密客户端。This quickstart application uses a client secret to identify itself as a confidential client. 由于客户端机密是以纯文本形式添加到项目文件的,因此为了安全起见,建议在生产环境中使用应用程序之前,使用证书来代替客户端机密。Because the client secret is added as plain text to your project files, for security reasons we recommend that you use a certificate instead of a client secret before using the application in a production environment. 有关如何使用证书的详细信息,请参阅用于应用程序身份验证的证书凭据For more information on how to use a certificate, see Certificate credentials for application authentication.

详细信息More information

示例工作原理How the sample works

显示本快速入门生成的示例应用程序的工作原理的示意图。

获取 MSALGet MSAL

MSAL for Java (MSAL4J) 是一个 Java 库,用于用户登录和请求令牌,此类令牌用于访问受 Microsoft 标识平台保护的 API。MSAL for Java (MSAL4J) is the Java library used to sign in users and request tokens that are used to access an API that's 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:

<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>msal4j</artifactId>
    <version>1.0.0</version>
</dependency>

在 build.gradle 中:In build.gradle:

compile group: 'com.microsoft.azure', name: 'msal4j', version: '1.0.0'

初始化 MSALInitialize MSAL

通过将以下代码添加到要在其中使用 MSAL4J 的文件的开头,来添加对 MSAL for Java 的引用:Add a reference to MSAL for Java by adding the following code at the start of the file where you'll be using MSAL4J:

import com.microsoft.aad.msal4j.*;

帮助和支持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

若要深入了解如何生成在 Microsoft 标识平台上将用户登录的 Web 应用,请参阅多部分方案系列:For a more in-depth discussion of building web apps that sign in users on the Microsoft identity platform, see the multipart scenario series: