通过适用于 JavaScript 的 Microsoft 身份验证库来使用 Azure AD B2CUse Microsoft Authentication Library for JavaScript to work with Azure AD B2C

借助适用于 JavaScript 的 Microsoft 身份验证库 (MSAL.js),JavaScript 应用程序开发人员可以使用 Azure Active Directory B2C (Azure AD B2C) 通过社交和本地标识对用户进行身份验证。Microsoft Authentication Library for JavaScript (MSAL.js) enables JavaScript developers to authenticate users with social and local identities using Azure Active Directory B2C (Azure AD B2C).

使用作为标识管理服务的 Azure AD B2C,可以自定义和控制客户的注册和登录方式,并在他们使用你的应用程序时管理其配置文件。By using Azure AD B2C as an identity management service, you can customize and control how your customers sign up, sign in, and manage their profiles when they use your applications. 使用 Azure AD B2C,还可以为应用程序在身份验证过程中显示的 UI 提供品牌标志并进行自定义。Azure AD B2C also enables you to brand and customize the UI that your application displays during the authentication process.

以下部分演示如何:The following sections demonstrate how to:

  • 保护 Node.js Web APIProtect a Node.js web API
  • 支持在单页应用程序 (SPA) 中登录,并调用受保护的 Web APISupport sign-in in a single-page application (SPA) and call that protected web API
  • 启用密码重置支持Enable password reset support

先决条件Prerequisites

如果尚未创建 Azure AD B2C 租户,请创建一个。If you haven't already, create an Azure AD B2C tenant.

Node.js Web APINode.js web API

以下步骤演示 Web API 如何使用 Azure AD B2C 来保护自身,并将所选范围公开给客户端应用程序。The following steps demonstrate how a web API can use Azure AD B2C to protect itself and expose selected scopes to a client application.

适用于 Node 的 MSAL.js 目前正在开发中。MSAL.js for Node is currently in development. 有关详细信息,请参阅 GitHub 上的路线图For more information, see the roadmap on GitHub. 我们目前建议使用 passport-azure-ad,它是由 Microsoft 开发并提供支持的适用于 Node.js 的身份验证库。We currently recommend using passport-azure-ad, an authentication library for Node.js developed and supported by Microsoft.

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

若要使用 Azure AD B2C 保护 Web API,首先需要注册该 Web API。To protect your web API with Azure AD B2C, you first need to register it. 请遵循注册应用程序来执行详细步骤。See Register your application for detailed steps.

步骤 2:下载示例应用程序Step 2: Download the sample application

下载示例作为 zip 文件,或从 GitHub 克隆:Download the sample as a zip file, or clone it from GitHub:

git clone https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi.git

步骤 3:配置身份验证Step 3: Configure authentication

  1. 打开示例中的 config.json 文件。Open the config.json file in the sample.

  2. 注册应用程序时,请使用前面获取的应用程序凭据配置示例。Configure the sample with the application credentials that you obtained earlier while registering your application. 更改以下代码行:将值替换为你的租户名称、客户端 ID 和策略名称。Change the following lines of code by replacing the values with your tenant name, client ID, and policy name.

         "credentials": {
             "tenantName": "<your-tenant-name>",
             "clientID": "<your-webapi-application-ID>"
         },
         "policies": {
             "policyName": "B2C_1_signupsignin1"
         },
         "resource": {
             "scope": ["demo.read"] 
         },
    

有关详细信息,请查看此 Node.js B2C Web API 示例For more information, check out this Node.js B2C web API sample.

JavaScript SPAJavaScript SPA

以下步骤演示单页应用程序如何使用 Azure AD B2C 进行注册和登录,并调用受保护的 Web API。The following steps demonstrate how a single-page application can use Azure AD B2C to sign up, sign in, and call a protected web API.

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

若要实现身份验证,首先需要注册你的应用程序。To implement authentication, you first need to register your application. 请遵循注册应用程序来执行详细步骤。See Register your application for detailed steps.

步骤 2:下载示例应用程序Step 2: Download the sample application

下载代码示例的 .ZIP 存档或克隆 GitHub 存储库:Download the code sample's .ZIP archive or clone the GitHub repository:

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

步骤 3:配置身份验证Step 3: Configure authentication

配置应用程序时有两个关注点:There are two points of interest in configuring your application:

  • 配置 API 终结点和公开的范围Configure API endpoint and exposed scopes
  • 配置身份验证参数和令牌范围Configure authentication parameters and token scopes
  1. 打开示例中的 apiConfig.js 文件。Open the apiConfig.js file in the sample.

  2. 注册 Web API 时,请使用前面获取的参数配置示例。Configure the sample with the parameters that you obtained earlier while registering your web API. 更改以下代码行:将值替换为你的 Web API 的地址和公开的范围。Change the following lines of code by replacing the values with the address of your web API and exposed scopes.

     // The current application coordinates were pre-registered in a B2C tenant.
     const apiConfig = {
         b2cScopes: ["https://fabrikamb2c.partner.onmschina.cn/helloapi/demo.read"], //API scopes you exposed during api registration
         webApi: "https://fabrikamb2chello.chinacloudsites.cn/hello"
     };
    
  3. 打开示例中的 authConfig.js 文件。Open the authConfig.js file in the sample.

  4. 注册单页应用程序时,请使用前面获取的参数配置示例。Configure the sample with the parameters that you obtained earlier while registering your single-page application. 更改以下代码行:将值替换为你的 ClientId、颁发机构元数据和令牌请求范围。Change the following lines of code by replacing the values with your ClientId, authority metadata and token request scopes.

     // Config object to be passed to Msal on creation.
     const msalConfig = {
         auth: {
             clientId: "e760cab2-b9a1-4c0d-86fb-ff7084abd902",
             authority: "https://fabrikamb2c.b2clogin.cn/fabrikamb2c.partner.onmschina.cn/B2C_1_signupsignin1",
             validateAuthority: false
         },
         cache: {
             cacheLocation: "localStorage", // This configures where your cache will be stored
             storeAuthStateInCookie: false // Set this to "true" to save cache in cookies
         }
     };
    
     // Add here scopes for id token to be used at the MS Identity Platform endpoint
     const loginRequest = {
         scopes: ["openid", "profile"],
     };
    

有关详细信息,请查看此 JavaScript B2C 单页应用程序示例For more information, check out this JavaScript B2C single-page application sample.

支持密码重置Support password reset

在本部分中,你将扩展单页应用程序以使用 Azure AD B2C 密码重置用户流。In this section, you extend your single-page application to use the Azure AD B2C password reset user flow. 尽管 MSAL 目前不原生支持多个用户流或自定义策略,但你可以使用库来处理常见的用例,例如密码重置。Although MSAL.js doesn't currently support multiple user flows or custom policies natively, you're able to use the library to handle common use cases like password reset.

以下步骤假定你已经按照前面的 JavaScript SPA 部分中的步骤进行操作。The following steps assume you've already followed the steps in the preceding JavaScript SPA section.

步骤 1:定义密码重置用户流的授权字符串Step 1: Define the authority string for password reset user flow

  1. 首先,创建一个对象,用于存储颁发机构 URI:First, create an object where you store your authority URIs:

        const b2cPolicies = {
            names: {
                signUpSignIn: "b2c_1_susi",
                forgotPassword: "b2c_1_reset"
            },
            authorities: {
                signUpSignIn: {
                    authority: "https://fabrikamb2c.b2clogin.cn/fabrikamb2c.partner.onmschina.cn/b2c_1_susi",
                },
                forgotPassword: {
                    authority: "https://fabrikamb2c.b2clogin.cn/fabrikamb2c.partner.onmschina.cn/b2c_1_reset",
                },
            },
        }
    
  2. 接下来,默认使用 signInSignUp 策略初始化 MSAL 对象(请参阅前面的代码片段)。Next, initialize your MSAL object with the signInSignUp policy as default (see the preceding code snippet). 当用户尝试登录时,将显示以下屏幕:When a user attempts to login, they're presented with the following screen:

    Azure AD B2C 显示的登录屏幕

步骤 2:捕获和处理登录方法中的身份验证错误Step 2: Catch and handle authentication errors in your login method

当某个用户选择“忘记密码”时,应用程序会引发一个错误,你的代码中应会捕获该错误,然后通过提供相应的用户流来处理此情况。When a user selects Forgot password, your application throws an error which you should catch in your code, and then handle by presenting the appropriate user flow. 在本例中,为 b2c_1_reset 密码重置流。In this case, the b2c_1_reset password reset flow.

  1. 按如下方式扩展登录方法:Extend your sign-in method as follows:

    function signIn() {
      myMSALObj.loginPopup(loginRequest)
        .then(loginResponse => {
            console.log("id_token acquired at: " + new Date().toString());
    
            if (myMSALObj.getAccount()) {
              updateUI();
            }
    
        }).catch(function (error) {
          console.log(error);
    
          // error handling
          if (error.errorMessage) {
            // check for forgot password error
            if (error.errorMessage.indexOf("AADB2C90118") > -1) {
    
              //call login method again with the password reset user flow
              myMSALObj.loginPopup(b2cPolicies.authorities.forgotPassword)
                .then(loginResponse => {
                  console.log(loginResponse);
                  window.alert("Password has been reset successfully. \nPlease sign-in with your new password.");
                })
            }
          }
        });
    }
    
  2. 上面的代码片段介绍了在代码 AADB2C90118 中捕获到错误后如何显示密码重置屏幕。The preceding code snippet shows you how to show the password reset screen after catching the error with the code AADB2C90118.

    重置密码后,用户返回应用程序并重新登录。After resetting their password, the user is returned back to the application to sign in again.

    Azure AD B2C 显示的密码重置流屏幕

    有关错误代码和异常处理的详细信息,请参阅 MSAL 错误和异常代码For more information about error codes and handling exceptions, see MSAL error and exception codes.

后续步骤Next steps

详细了解 Azure AD B2C 概念:Learn more about these Azure AD B2C concepts: