教程:使用 Azure AD B2C 在单页应用程序中启用身份验证Tutorial: Enable authentication in a single-page application with Azure AD B2C

本教程介绍如何使用 Azure Active Directory B2C (Azure AD B2C) 在单页应用程序 (SPA) 中进行用户登录和注册。This tutorial shows you how to use Azure Active Directory B2C (Azure AD B2C) to sign up and sign in users in a single-page application (SPA).

本教程是由两个部分组成的教程系列的第一部分,将介绍以下操作:In this tutorial, the first in a two-part series:

  • 将回复 URL 添加到在 Azure AD B2C 租户中注册的应用程序Add a reply URL to an application registered in your Azure AD B2C tenant
  • 从 GitHub 下载代码示例Download a code sample from GitHub
  • 修改示例应用程序的代码,使其适用于你的租户Modify the sample application's code to work with your tenant
  • 使用注册/登录用户流进行注册Sign up using your sign-up/sign-in user flow

本教程系列中的下一篇教程将启用代码示例的 Web API 部分。The next tutorial in the series enables the web API portion of the code sample.

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

先决条件Prerequisites

在继续执行本教程中的步骤以前,需将以下 Azure AD B2C 资源准备到位:You need the following Azure AD B2C resources in place before continuing with the steps in this tutorial:

另外,需要在本地开发环境中备好以下项:Additionally, you need the following in your local development environment:

更新应用程序Update the application

在按照先决条件完成的第二个教程中,你已在 Azure AD B2C 中注册了 Web 应用程序。In the second tutorial that you completed as part of the prerequisites, you registered a web application in Azure AD B2C. 若要使用本教程中的代码示例实现通信,请将一个回复 URL(也称为重定向 URI)添加到应用程序注册。To enable communication with the code sample in this tutorial, add a reply URL (also called a redirect URI) to the application registration.

要更新 Azure AD B2C 租户中的应用程序,可以使用新的统一“应用注册”体验或旧版“应用程序(旧版)”体验 。To update an application in your Azure AD B2C tenant, you can use our new unified App registrations experience or our legacy Applications (Legacy) experience. 详细了解此新体验Learn more about the new experience.

  1. 登录 Azure 门户Sign in to the Azure portal.
  2. 在顶部菜单中选择“目录 + 订阅”筛选器,然后选择包含Azure AD B2C 租户的目录。Select the Directory + subscription filter in the top menu, and then select the directory that contains your Azure AD B2C tenant.
  3. 在左侧菜单中,选择“Azure AD B2C”。In the left menu, select Azure AD B2C. 或者,选择“所有服务”并搜索并选择“Azure AD B2C”。Or, select All services and search for and select Azure AD B2C.
  4. 依次选择“应用注册(预览版)”、“拥有的应用程序”选项卡,然后选择“webapp1”应用程序 。Select App registrations, select the Owned applications tab, and then select the webapp1 application.
  5. 在“Web”下,选择“添加 URI”链接,输入 http://localhost:6420Under Web, select the Add URI link, enter http://localhost:6420.
  6. 在“隐式授权”下,选中“访问令牌”和“ID 令牌”复选框,然后选择“保存”。Under Implicit Grant, select the checkboxes for Access Tokens and ID Tokens and then select Save.
  7. 选择“概述”。Select Overview.
  8. 记录“应用程序(客户端) ID”,以便稍后在单页 Web 应用程序中更新代码时使用。Record the Application (client) ID for use in a later step when you update the code in the single-page web application.

获取示例代码Get the sample code

在本教程中,你将配置从 GitHub 下载的代码示例,以其适用于你的 B2C 租户。In this tutorial, you configure a code sample that you download from GitHub to work with your B2C tenant. 该示例演示了单页应用程序如何使用 Azure AD B2C 进行用户注册和登录,并调用受保护的 Web API(将在本系列教程的下一篇教程中启用该 Web API)。The sample demonstrates how a single-page application can use Azure AD B2C for user sign-up and sign-in, and to call a protected web API (you enable the web API in the next tutorial in the series).

从 GitHub 下载 zip 文件或克隆该示例。Download a zip file or clone the sample from GitHub.

git clone https://github.com/Azure-Samples/active-directory-b2c-javascript-msal-singlepageapp.git

更新示例Update the sample

获得示例以后,即可使用在此前的步骤中记录的 Azure AD B2C 租户名称和应用程序 ID 来更新代码。Now that you've obtained the sample, update the code with your Azure AD B2C tenant name and the application ID you recorded in an earlier step.

  1. 打开 JavaScriptSPA 文件夹中的 authConfig.js 文件。 Open the authConfig.js file inside the JavaScriptSPA folder.

  2. msalConfig 对象中:In the msalConfig object, update:

    • 使用在前面的步骤中记下的“应用程序(客户端) ID”值更新 clientIdclientId with value with the Application (client) ID you recorded in an earlier step
    • 使用你的 Azure AD B2C 租户名称,以及在先决条件部分中创建的注册/登录用户流的名称(例如 B2C_1_signupsignin1)更新 authority URIauthority URI with your Azure AD B2C tenant name and the name of the sign-up/sign-in user flow you created as part of the prerequisites (for example, B2C_1_signupsignin1)
    const msalConfig = {
        auth: {
          clientId: "00000000-0000-0000-0000-000000000000", // Replace this value with your Application (client) ID
          authority: b2cPolicies.authorities.signUpSignIn.authority,
          validateAuthority: false
        },
        cache: {
          cacheLocation: "localStorage",
          storeAuthStateInCookie: true
        }
    };
    
    const loginRequest = {
       scopes: ["openid", "profile"],
    };
    
    const tokenRequest = {
      scopes: apiConfig.b2cScopes // i.e. ["https://fabrikamb2c.partner.onmschina.cn/helloapi/demo.read"]
    };
    

运行示例Run the sample

  1. 打开控制台窗口,切换到包含此示例的目录。Open a console window and change to the directory containing the sample. 例如:For example:

    cd active-directory-b2c-javascript-msal-singlepageapp
    
  2. 运行以下命令:Run the following commands:

    npm install && npm update
    npm start
    

    控制台窗口显示本地运行的 Node.js 服务器的端口号:The console window displays the port number of the locally running Node.js server:

    Listening on port 6420...
    
  3. 浏览到 http://localhost:6420,查看在本地计算机上运行的 Web 应用程序。Browse to http://localhost:6420 to view the web application running on your local machine.

    显示了本地运行的单页应用程序的 Web 浏览器

使用电子邮件地址注册Sign up using an email address

此示例应用程序支持注册、登录和密码重置。This sample application supports sign up, sign in, and password reset. 在本教程中,你将使用电子邮件地址进行注册。In this tutorial, you sign up using an email address.

  1. 选择“登录”以启动在前面步骤中指定的 B2C_1_signupsignin1 用户流。Select Sign In to initiate the B2C_1_signupsignin1 user flow you specified in an earlier step.

  2. Azure AD B2C 会显示一个包含注册链接的登录页。Azure AD B2C presents a sign-in page that includes a sign up link. 由于你还没有帐户,因此请选择“立即注册”链接。Since you don't yet have an account, select the Sign up now link.

  3. 注册工作流会显示一个页面,用于收集用户的标识并通过电子邮件地址对其进行验证。The sign up workflow presents a page to collect and verify the user's identity using an email address. 注册工作流还会收集用户的密码和所请求的属性(在用户流中定义)。The sign up workflow also collects the user's password and the requested attributes defined in the user flow.

    请使用有效的电子邮件地址,并使用验证码进行验证。Use a valid email address and validate using the verification code. 设置密码。Set a password. 输入请求的属性的值。Enter values for the requested attributes.

    Azure AD B2C 用户流显示的注册页

  4. 选择“创建”,在 Azure AD B2C 目录中创建本地帐户。Select Create to create a local account in the Azure AD B2C directory.

选择“创建”时,应用程序会显示已登录用户的名称。When you select Create, the application shows the name of the signed in user.

显示了包含已登录用户的单页应用程序的 Web 浏览器

若要测试登录,请选择“注销”按钮,然后选择“登录”,并使用注册时输入的电子邮件地址和密码进行登录。 If you'd like to test sign-in, select the Sign Out button, then select Sign In and sign in with the email address and password you entered when you signed up.

调用 API 时会发生什么情况?What about calling the API?

如果在登录后选择“调用 API”按钮,将会看到注册/登录用户流页面,而不是 API 调用结果。If you select the Call API button after signing in, you're presented with the sign-up/sign-in user flow page instead of the results of the API call. 这种情况是意料之中的,因为尚未配置应用程序的 API 部分来与你的 Azure AD B2C 租户中注册的 Web API 应用程序进行通信。This is expected because you haven't yet configured the API portion of the application to communicate with a web API application registered in your Azure AD B2C tenant.

此时,应用程序仍会尝试与演示租户 (fabrikamb2c.partner.onmschina.cn) 中注册的 API 进行通信,同时,由于你尚未在该租户中进行身份验证,将显示注册/登录页。At this point, the application is still trying to communicate with the API registered in the demo tenant (fabrikamb2c.partner.onmschina.cn), and because you're not authenticated with that tenant, the sign-up/sign-in page is displayed.

请继续学习本教程系列的下一篇教程来启用受保护的 API(参阅后续步骤部分)。Move on to the next tutorial in the series in to enable the protected API (see the Next steps section).

后续步骤Next steps

在本教程中,你已将某个单页应用程序配置为使用 Azure AD B2C 租户中的用户流来提供注册和登录功能。In this tutorial, you configured a single-page application to work with a user flow in your Azure AD B2C tenant to provide sign up and sign in capability. 你已完成以下步骤:You completed these steps:

  • 将回复 URL 添加到了在 Azure AD B2C 租户中注册的应用程序Added a reply URL to an application registered in your Azure AD B2C tenant
  • 从 GitHub 下载了代码示例Downloaded a code sample from GitHub
  • 修改了示例应用程序的代码,使其适用于你的租户Modified the sample application's code to work with your tenant
  • 使用注册/登录用户流完成了注册Signed up using your sign-up/sign-in user flow

现在可转到此系列的下一教程,了解如何授予用户访问权限,以便从 SPA 访问受保护的 Web API:Now move on to the next tutorial in the series to grant access to a protected web API from the SPA: