教程:在 Angular 单页应用程序中添加登录和退出登录

本教程是演示如何生成 Angular 单页应用 (SPA) 的系列教程的第 3 部分,该应用使用 Microsoft 标识平台进行身份验证。 在本教程中,你将向 Angular SPA 添加登录和退出登录体验。

本教程的内容:

  • 向应用添加登录和退出登录功能。

先决条件

向应用添加登录和退出登录功能

若要在 Angular 应用程序中启用登录和退出登录功能,请执行以下步骤:

  1. 打开 src/app/app.component.html 文件并将其内容替换为以下代码。

    <a class="navbar navbar-dark bg-primary" variant="dark" href="/">
        <a class="navbar-brand"> Microsoft Identity Platform </a>
        <a>
            <button *ngIf="!loginDisplay" class="btn btn-secondary" (click)="login()">Sign In</button>
            <button *ngIf="loginDisplay" class="btn btn-secondary" (click)="logout()">Sign Out</button>
        </a>
    </a>
    <a class="profileButton">
        <a [routerLink]="['profile']" class="btn btn-secondary" *ngIf="loginDisplay">View Profile</a> 
    </a>
    <div class="container">
        <router-outlet></router-outlet>
    </div>
    

    该代码在 Angular 应用中实现导航栏。 它根据用户身份验证状态动态显示“登录”和“退出登录”按钮,并包含面向已登录用户的“查看个人资料”按钮,从而增强应用程序的用户界面。 选择按钮时会调用 src/app/app.component.ts 中的 login()logout() 方法。

  2. 打开 src/app/app-routing.module.ts 文件并将其内容替换为以下代码。

    // Required for Angular
    import { NgModule } from '@angular/core';
    
    // Required for the Angular routing service
    import { Routes, RouterModule } from '@angular/router';
    
    // Required for the "Profile" page
    import { ProfileComponent } from './profile/profile.component';
    
    // Required for the "Home" page
    import { HomeComponent } from './home/home.component';
    
    // MsalGuard is required to protect routes and require authentication before accessing protected routes
    import { MsalGuard } from '@azure/msal-angular';
    
    // Define the possible routes
    // Specify MsalGuard on routes to be protected
    // '**' denotes a wild card
    const routes: Routes = [
      {
        path: 'profile',
        component: ProfileComponent,
        canActivate: [
          MsalGuard
        ]
      },
      {
        path: '**',
        component: HomeComponent
      }
    ];
    
    // Create an NgModule that contains all the directives for the routes specified above
    @NgModule({
      imports: [RouterModule.forRoot(routes, {
        useHash: true
      })],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    该代码片段通过为 Profile 和 Home 组件建立路径来配置 Angular 应用程序中的路由。 它使用 MsalGuard 在 Profile 路由上强制执行身份验证,而所有不匹配的路径都会重定向到 Home 组件。

  3. 打开 src/app/home/home.component.ts 文件并将其内容替换为以下代码。

    // Required for Angular
    import { Component, OnInit } from '@angular/core';
    
    // Required for MSAL
    import { MsalBroadcastService, MsalService } from '@azure/msal-angular';
    
    // Required for Angular multi-browser support
    import { EventMessage, EventType, AuthenticationResult } from '@azure/msal-browser';
    
    // Required for RJXS observables
    import { filter } from 'rxjs/operators';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html'
    })
    export class HomeComponent implements OnInit {
      constructor(
        private authService: MsalService,
        private msalBroadcastService: MsalBroadcastService
      ) { }
    
      // Subscribe to the msalSubject$ observable on the msalBroadcastService
      // This allows the app to consume emitted events from MSAL
      ngOnInit(): void {
        this.msalBroadcastService.msalSubject$
          .pipe(
            filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),
          )
          .subscribe((result: EventMessage) => {
            const payload = result.payload as AuthenticationResult;
            this.authService.instance.setActiveAccount(payload.account);
          });
      }
    }
    

    该代码会设置一个名为 HomeComponent 的与 Microsoft 身份验证库 (MSAL) 集成的 Angular 组件。 在 ngOnInit 生命周期挂钩中,组件会订阅可从 MsalBroadcastService 观测到的 msalSubject$,筛选登录成功事件。 发生登录事件时,它会检索身份验证结果,并在 MsalService 中设置活动帐户,使应用程序能够管理用户会话。

  4. 打开 src/app/home/home.component.html 文件并将其内容替换为以下代码。

    <div class="title">
        <h5>
            Welcome to the Microsoft Authentication Library For Javascript - Angular SPA
        </h5>
        <p >View your data from Microsoft Graph by clicking the "View Profile" link above.</p>
    </div>
    

    该代码会欢迎用户访问应用,并通过单击“查看个人资料”链接提示他们查看其 Microsoft Graph 数据。

  5. 打开 src/main.ts 文件并将其内容替换为以下代码。

    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    
    import { AppModule } from './app/app.module';
    
    platformBrowserDynamic().bootstrapModule(AppModule)
      .catch(err => console.error(err));
    

    该代码片段会从 Angular 的平台浏览器动态模块导入 platformBrowserDynamic,并从应用程序的模块文件导入 AppModule。 然后,它使用 platformBrowserDynamic() 启动 AppModule,初始化 Angular 应用程序。 启动过程中发生的任何错误都会被捕获并记录到控制台。

  6. 打开 src/index.html 文件并将其内容替换为以下代码。

    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>MSAL For Javascript - Angular SPA</title>
      </head>
      <body>
        <app-root></app-root>
        <app-redirect></app-redirect>
      </body>
    </html>
    

    该代码片段会定义一个 HTML5 文档,以英语作为语言,字符编码为 UTF-8。 它将标题设置为“MSAL For Javascript - Angular SPA”。正文包含 <app-root> 组件作为主要入口点,<app-redirect> 组件用于重定向功能。

  7. 打开 src/styles.css 文件并将其内容替换为以下代码。

    body {
      margin: 0;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
        'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
        sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }
    
    code {
      font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
        monospace;
    }
    
    .app {
      text-align: center;
      padding: 8px;
    }
    
    .title{
      text-align: center;
      padding: 18px;
    }
    
    
    .profile{
      text-align: center;
      padding: 18px;
    }
    
    .profileButton{
      display: flex;
      justify-content: center;
      padding: 18px;
    }
    

    该 CSS 代码会设置网页样式,将正文字体设置为新式 sans-serif 堆栈、移除默认边距并应用字体平滑,从而提高可读性。 它会将文本居中,并向 .app.title.profile 类添加填充,而 .profileButton 类使用弹性框来居中其元素。

后续步骤