快速上手:在单页应用 (SPA) 中让用户登录并调用 Microsoft Graph API

在本快速入门中,你将使用示例单页应用(SPA)来演示如何使用 授权代码流 和代码交换证明密钥(PKCE)登录用户,并调用Microsoft图形 API。 此示例使用 Microsoft身份验证库 来处理身份验证。

先决条件

  • 拥有有效订阅的 Azure 帐户。 如果还没有帐户,请创建一个帐户
  • Azure 帐户必须拥有管理应用程序的权限。 以下任何Microsoft Entra 角色都包含所需的权限:
    • 应用程序管理员
    • 应用程序开发人员
  • 工作人员租户。 可以使用默认目录或 设置新租户
  • Visual Studio Code 或其他代码编辑器。

克隆或下载示例应用程序

若要获取示例应用程序,可以从 GitHub 克隆它,也可以将其下载为 .zip 文件。

  • 若要克隆示例,请打开命令提示符并导航到要创建项目的位置,然后输入以下命令:

    console
    git clone https://github.com/Azure-Samples/ms-identity-docs-code-javascript.git
    
  • 下载 .zip 文件。 将其解压缩到名称长度少于 260 个字符的文件路径。

配置项目

  1. 在 IDE 中,打开包含示例的项目文件夹 ms-identity-docs-code-javascript/angular-spa

  2. 打开 angular-spa/src/app/app.module.ts ,并使用管理中心中记录的信息更新以下值。

    JavaScript
    // Required for Angular multi-browser support
    import { BrowserModule } from '@angular/platform-browser';
    
    // Required for Angular
    import { NgModule } from '@angular/core';
    
    // Required modules and components for this application
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { ProfileComponent } from './profile/profile.component';
    import { HomeComponent } from './home/home.component';
    
    // HTTP modules required by MSAL
    import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
    
    // Required for MSAL
    import { IPublicClientApplication, PublicClientApplication, InteractionType, BrowserCacheLocation, LogLevel } from '@azure/msal-browser';
    import { MsalGuard, MsalInterceptor, MsalBroadcastService, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalGuardConfiguration, MsalRedirectComponent } from '@azure/msal-angular';
    
    const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1;
    
    export function MSALInstanceFactory(): IPublicClientApplication {
      return new PublicClientApplication({
        auth: {
          // 'Application (client) ID' of app registration in the Microsoft Entra admin center - this value is a GUID
          clientId: "Enter_the_Application_Id_Here",
          // Full directory URL, in the form of https://login.partner.microsoftonline.cn/<tenant>
          authority: "https://login.partner.microsoftonline.cn/Enter_the_Tenant_Info_Here",
          // Must be the same redirectUri as what was provided in your app registration.
          redirectUri: "http://localhost:4200",
        },
        cache: {
          cacheLocation: BrowserCacheLocation.LocalStorage,
          storeAuthStateInCookie: isIE
        }
      });
    }
    
    // MSAL Interceptor is required to request access tokens in order to access the protected resource (Graph)
    export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
      const protectedResourceMap = new Map<string, Array<string>>();
      protectedResourceMap.set('https://microsoftgraph.chinacloudapi.cn/v1.0/me', ['https://microsoftgraph.chinacloudapi.cn/user.read']);
    
      return {
        interactionType: InteractionType.Redirect,
        protectedResourceMap
      };
    }
    
    // MSAL Guard is required to protect routes and require authentication before accessing protected routes
    export function MSALGuardConfigFactory(): MsalGuardConfiguration {
      return { 
        interactionType: InteractionType.Redirect,
        authRequest: {
          scopes: ['https://microsoftgraph.chinacloudapi.cn/user.read']
        }
      };
    }
    
    // Create an NgModule that contains the routes and MSAL configurations
    @NgModule({
      declarations: [
        AppComponent,
        HomeComponent,
        ProfileComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        MsalModule
      ],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: MsalInterceptor,
          multi: true
        },
        {
          provide: MSAL_INSTANCE,
          useFactory: MSALInstanceFactory
        },
        {
          provide: MSAL_GUARD_CONFIG,
          useFactory: MSALGuardConfigFactory
        },
        {
          provide: MSAL_INTERCEPTOR_CONFIG,
          useFactory: MSALInterceptorConfigFactory
        },
        MsalService,
        MsalGuard,
        MsalBroadcastService
      ],
      bootstrap: [AppComponent, MsalRedirectComponent]
    })
    export class AppModule { }
    
    • clientId - 应用程序的标识符,也称为客户端。 将引号中的文本替换为前面记录的 应用程序(客户端)ID 值。
    • authority - 颁发机构是一个 URL,表示 MSAL 可从中请求令牌的目录。 请将Enter_the_Tenant_Info_Here替换为先前记录的目录(租户)ID值。
    • redirectUri - 应用程序的重定向 URI。 如有必要,请将引号中的文本替换为前面记录的重定向 URI。

运行应用程序并登录和注销

使用 Node.js 在 Web 服务器中运行项目:

  1. 若要启动服务器,请从项目目录中运行以下命令:

    console
    cd angular-spa
    npm install
    npm start
    
  2. 复制终端中显示的 https URL(例如 https://localhost:4200),并将其粘贴到浏览器地址栏中。 建议使用专用或隐身浏览器会话。

  3. 按照步骤操作,并输入必要的详细信息,以使用 Microsoft 帐户登录。 系统会要求你提供电子邮件地址,以便向你发送一次性密码。 出现提示时输入代码。

  4. 该应用程序将请求维持你对已授权访问的数据的访问权限,以及让你登录并读取个人资料的权限。 选择 “接受”。 将显示以下屏幕截图,指示已登录到应用程序,并从 Microsoft Graph API 访问配置文件详细信息。

    描述 API 调用结果的 JavaScript 应用的屏幕截图。

从应用程序注销

  1. 在页面上找到 “注销 ”按钮,然后选择它。
  2. 系统将提示你选择要退出登录的帐户。 选择用于登录的帐户。

此时会显示一条消息,指示你已注销。现在可以关闭浏览器窗口。