教程:使用本机身份验证 JavaScript SDK 将用户注册到 Angular 单页应用(预览版)

适用于绿色圆圈,带有白色复选标记符号,指示以下内容适用于外部租户。 外部租户(了解详细信息

本教程介绍如何构建一个 Angular 单页应用,该应用使用本机身份验证的 JavaScript SDK 注册用户。

在本教程中,你将:

  • 创建 Angular Next.js 项目。
  • 将 MSAL JS SDK 添加到其中。
  • 添加应用的 UI 组件。
  • 设置项目以注册用户。

先决条件

创建 React 项目并安装依赖项

在计算机中选择的位置,运行以下命令以创建名为 reactspa 的新 Angular 项目,导航到项目文件夹,然后安装包:

ng new angularspa
cd angularspa

成功运行命令后,应具有具有以下结构的应用:

angularspa/
└──node_modules/
   └──...
└──public/
   └──...
└──src/
   └──app/
      └──app.component.html
      └──app.component.scss
      └──app.component.ts
      └──app.modules.ts
      └──app.config.ts
      └──app.routes.ts
   └──index.html
   └──main.ts
   └──style.scss
└──angular.json
└──package-lock.json
└──package.json
└──README.md
└──tsconfig.app.json
└──tsconfig.json
└──tsconfig.spec.json

将 JavaScript SDK 添加到项目

若要在应用中使用本机身份验证 JavaScript SDK,请使用终端通过以下命令安装它:

npm intall @azure/msal-browser

本机身份验证功能是库的 azure-msal-browser 一部分。 若要使用本机身份验证功能,请从中 @azure/msal-browser/custom-auth导入 。 例如:

  import CustomAuthPublicClientApplication from "@azure/msal-browser/custom-auth";

添加客户端配置

在本部分中,将定义本机身份验证公共客户端应用程序的配置,使它能够与 SDK 的接口进行交互。 为此,

  1. 创建名为 src/app/config/auth-config.ts 的文件,然后添加以下代码:

    export const customAuthConfig: CustomAuthConfiguration = {
        customAuth: {
            challengeTypes: ["password", "oob", "redirect"],
            authApiProxyUrl: "http://localhost:3001/api",
        },
        auth: {
            clientId: "Enter_the_Application_Id_Here",
            authority: "https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com",
            redirectUri: "/",
            postLogoutRedirectUri: "/",
            navigateToLoginRequestUrl: false,
        },
        cache: {
            cacheLocation: "sessionStorage",
        },
        system: {
            loggerOptions: {
                loggerCallback: (level: LogLevel, message: string, containsPii: boolean) => {
                    if (containsPii) {
                        return;
                    }
                    switch (level) {
                        case LogLevel.Error:
                            console.error(message);
                            return;
                        case LogLevel.Info:
                            console.info(message);
                            return;
                        case LogLevel.Verbose:
                            console.debug(message);
                            return;
                        case LogLevel.Warning:
                            console.warn(message);
                            return;
                    }
                },
            },
        },
    };
    

    在代码中,找到占位符:

    • Enter_the_Application_Id_Here 然后将其替换为之前注册的应用的应用程序(客户端)ID。

    • Enter_the_Tenant_Subdomain_Here 然后将其替换为Microsoft Entra 管理中心中的租户子域。 例如,如果租户主域名是 contoso.onmicrosoft.com,请使用 contoso。 如果没有租户名称,请了解如何 阅读租户详细信息

  2. 创建名为 src/app/services/auth.service.ts 的文件,然后添加以下代码:

    import { Injectable } from '@angular/core';
    import { CustomAuthPublicClientApplication, ICustomAuthPublicClientApplication } from '@azure/msal-browser/custom-auth';
    import { customAuthConfig } from '../config/auth-config';
    
    @Injectable({ providedIn: 'root' })
    export class AuthService {
      private authClientPromise: Promise<ICustomAuthPublicClientApplication>;
      private authClient: ICustomAuthPublicClientApplication | null = null;
    
      constructor() {
        this.authClientPromise = this.init();
      }
    
      private async init(): Promise<ICustomAuthPublicClientApplication> {
        this.authClient = await CustomAuthPublicClientApplication.create(customAuthConfig);
        return this.authClient;
      }
    
      getClient(): Promise<ICustomAuthPublicClientApplication> {
        return this.authClientPromise;
      }
    }
    

创建注册组件

  1. 创建名为 /app/components 的目录。

  2. 运行以下命令,使用 Angular CLI 为 组件 文件夹中的注册页生成新组件:

    cd components
    ng generate component sign-up
    
  3. 打开注册/sign-up.component.ts文件,然后将其内容替换为注册.component 中的内容

  4. 打开 注册/sign-up.component.html 文件,并在 html 文件中添加代码。

    • sign-up.component.ts文件中的以下逻辑确定用户在启动注册过程后下一步需要执行的作。 根据结果,它会在 sign-up.component.html 中显示密码表单或验证码表单,以便用户可以继续注册流:

         const attributes: UserAccountAttributes = {
                     givenName: this.firstName,
                     surname: this.lastName,
                     jobTitle: this.jobTitle,
                     city: this.city,
                     country: this.country,
                 };
         const result = await client.signUp({
                     username: this.email,
                     attributes,
                 });
      
         if (result.isPasswordRequired()) {
             this.showPassword = true;
             this.showCode = false;
         } else if (result.isCodeRequired()) {
             this.showPassword = false;
             this.showCode = true;
         }
      

      SDK 的实例方法启动 signUp() 注册流。

    • 如果希望用户在注册完成后立即启动登录流,请使用以下代码片段:

      <div *ngIf="isSignedUp">
          <p>The user has been signed up, please click <a href="/sign-in">here</a> to sign in.</p>
      </div>
      
  5. 打开 注册/sign-up.component.scss 文件,然后添加以下 样式文件

注册后自动登录(可选)

可以在成功注册后自动登录用户,而无需启动新的登录流。 为此,请使用以下代码片段。 请参阅 注册/sign-up.component.ts的完整示例:

    if (this.signUpState instanceof SignUpCompletedState) {
        const result = await this.signUpState.signIn();
    
        if (result.isFailed()) {
            this.error = result.error?.errorData?.errorDescription || "An error occurred during auto sign-in";
        }
    
        if (result.isCompleted()) {
            this.userData = result.data;
            this.signUpState = result.state;
            this.isSignedUp = true;
            this.showCode = false;
            this.showPassword = false;
        }
    }

在用户中自动签名时,请在 注册/sign-up.component.html html 文件中使用以下代码片段。

    <div *ngIf="userData && !isSignedIn">
        <p>Signed up complete, and signed in as {{ userData?.getAccount()?.username }}</p>
    </div>
    <div *ngIf="isSignedUp && !userData">
        <p>Sign up completed! Signing you in automatically...</p>
    </div>

更新应用路由

  1. 打开 src/app/app.route.ts 文件,然后添加注册组件的路由:

    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { SignUpComponent } from './components/sign-up/sign-up.component';
    import { AuthService } from './services/auth.service';
    import { AppComponent } from './app.component';
    
    export const routes: Routes = [
        { path: 'sign-up', component: SignUpComponent },
    ];
    
    @NgModule({
        imports: [
            RouterModule.forRoot(routes),
            SignUpComponent,
        ],
        providers: [AuthService],
        bootstrap: [AppComponent]
    })
    export class AppRoutingModule { }
    

测试注册流

  1. 若要启动 CORS 代理服务器,请在终端中运行以下命令:

    npm run cors
    
  2. 若要启动应用程序,请在终端中运行以下命令:

    npm start
    
  3. 打开 Web 浏览器并导航到 http://localhost:4200/sign-up。 此时会显示注册表单。

  4. 若要注册帐户,请输入详细信息,选择“ 继续 ”按钮,然后按照提示作。

后续步骤