快速入门:生成使用 Azure Active Directory 登录和注销的 AngularJS 单页应用Quickstart: Build an AngularJS single-page app for sign-in and sign out with Azure Active Directory

适用于:Applies to:
  • Azure AD v1.0 终结点Azure AD v1.0 endpoint
  • Azure Active Directory Authentication Library (ADAL)Azure Active Directory Authentication Library (ADAL)

使用 Azure Active Directory (Azure AD) 可以简单直接地在单页面应用程序中添加登录、注销和安全 OAuth API 调用。Azure Active Directory (Azure AD) makes it simple and straightforward for you to add sign-in, sign-out, and secure OAuth API calls to your single-page apps. 它允许应用使用用户的 Windows Server Active Directory 帐户对用户进行身份验证,并使用 Azure AD 帮助保护的任何 Web API(例如 Office 365 API 或 Azure API)。It enables your apps to authenticate users with their Windows Server Active Directory accounts and consume any web API that Azure AD helps protect, such as the Office 365 APIs or the Azure API.

对于浏览器中运行的 javascript 应用程序,Azure AD 提供 Active Directory 身份验证库 (ADAL),即 adal.js。For JavaScript applications running in a browser, Azure AD provides the Active Directory Authentication Library (ADAL), or adal.js. adal.js 的唯一用途就是方便应用获取访问令牌。The sole purpose of adal.js is to make it easy for your app to get access tokens.

本快速入门将介绍如何生成具有以下功能的 AngularJS 待办事项列表应用程序:In this quickstart, you'll learn how to build an AngularJS To Do List application that:

  • 使用 Azure AD 作为标识提供程序将用户登录到应用。Signs the user in to the app by using Azure AD as the identity provider.
  • 显示有关用户的一些信息。Displays some information about the user.
  • 使用 Azure AD 提供的持有者令牌安全调用应用的待办事项列表 API。Securely calls the app's To Do List API by using bearer tokens from Azure AD.
  • 从应用中注销用户。Signs the user out of the app.

要构建完整的工作应用程序,需要:To build the complete, working application, you'll need to:

  1. 将应用注册到 Azure AD。Register your app with Azure AD.
  2. 安装 ADAL 并配置单页面应用。Install ADAL and configure the single-page app.
  3. 使用 ADAL 帮助保护单页面应用中的页面。Use ADAL to help secure pages in the single-page app.

先决条件Prerequisites

开始前,请完成这些先决条件:To get started, complete these prerequisites:

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

若要使应对用户进行身份验证并获取令牌,首先需要在 Azure AD 租户中注册该应用:To enable your app to authenticate users and get tokens, you first need to register it in your Azure AD tenant:

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 如果登录到多个目录,可能需要确保正在查看正确目录。If you are signed in to multiple directories, you may need to ensure you are viewing the correct directory. 若要执行此操作,在顶部栏上,单击你的帐户。To do so, on the top bar, click your account. 在“目录”列表下选择要注册应用程序的 Azure AD 租户。Under the Directory list, choose the Azure AD tenant where you want to register your application.

  3. 在左窗格中,单击“所有服务”,并选择“Azure Active Directory”。Click All services in the left pane, and then select Azure Active Directory.

  4. 单击“应用注册”,并选择“添加”。Click App registrations, and then select Add.

  5. 根据提示创建一个新的 Web 应用程序和/或 Web API:Follow the prompts and create a new web application and/or web API:

    • 名称向用户描述应用程序。Name describes your application to users.
    • “登录 URL”是 Azure AD 要将令牌返回到的位置。Sign-on URL is the location to which Azure AD will return tokens. 本示例的默认位置是 https://localhost:44326/The default location for this sample is https://localhost:44326/.
  6. 完成注册后,Azure AD 将向应用分配唯一应用程序 ID。After you finish registration, Azure AD assigns a unique application ID to your app. 在后面的部分中会用到此值,因此,请从应用程序选项卡中复制此值。You'll need this value in the next sections, so copy it from the application tab.

  7. Adal.js 使用 OAuth 隐式流来与 Azure AD 通信。Adal.js uses the OAuth implicit flow to communicate with Azure AD. 必须为应用程序启用隐式流:You must enable the implicit flow for your application:

    1. 单击应用程序,并选择“清单”打开内联清单编辑器。Click the application and select Manifest to open the inline manifest editor.
    2. 找到 oauth2AllowImplicitFlow 属性。Locate the oauth2AllowImplicitFlow property. 将其值设置为 trueSet its value to true.
    3. 单击“保存”以保存清单。Click Save to save the manifest.
  8. 针对应用程序,在租户中授予权限。Grant permissions across your tenant for your application. 转到“设置”>“所需的权限”,选择顶部栏上的“授予权限”按钮。Go to Settings > Required permissions, and select the Grant permissions button on the top bar.

  9. 请选择“是”以确认。Select Yes to confirm.

步骤 2:安装 ADAL 并配置单页面应用Step 2: Install ADAL and configure the single-page app

将应用程序注册到 Azure AD 后,可以安装 adal.js 并编写标识相关的代码。Now that you have an application in Azure AD, you can install adal.js and write your identity-related code.

配置 JavaScript 客户端Configure the JavaScript client

首先,使用程序包管理器控制台将 adal.js 添加到 TodoSPA 项目:Begin by adding adal.js to the TodoSPA project by using the Package Manager Console:

  1. 下载 adal.js 并将其添加到 App/Scripts/ 项目目录。Download adal.js and add it to the App/Scripts/ project directory.

  2. 下载 adal-angular.js 并将其添加到 App/Scripts/ 项目目录。Download adal-angular.js and add it to the App/Scripts/ project directory.

  3. index.html 将每个脚本加载到 </body> 的末尾之前:Load each script before the end of the </body> in index.html:

    ...
    <script src="App/Scripts/adal.js"></script>
    <script src="App/Scripts/adal-angular.js"></script>
    ...
    

配置后端服务器Configure the back end server

要使单页面应用的后端待办事项列表 API 接受来自浏览器的令牌,后端需要有关应用注册的配置信息。For the single-page app's back-end To Do List API to accept tokens from the browser, the back end needs configuration information about the app registration. 在 TodoSPA 项目中,打开 web.configIn the TodoSPA project, open web.config. 替换 <appSettings> 部分中的元素值,反映在 Azure 门户中使用的值。Replace the values of the elements in the <appSettings> section to reflect the values that you used in the Azure portal. 只要使用 ADAL,代码就会引用这些值。Your code will reference these values whenever it uses ADAL.

  • ida:Tenant 是 Azure AD 租户的域,例如,contoso.partner.onmschina.cn。ida:Tenant is the domain of your Azure AD tenant--for example, contoso.partner.onmschina.cn.
  • ida:Audience 是从门户复制的应用程序的客户端 ID。ida:Audience is the client ID of your application that you copied from the portal.

步骤 3:使用 ADAL 帮助保护单页面应用中的页面Step 3: Use ADAL to help secure pages in the single-page app

Adal.js 与 AngularJS 路由和 HTTP 提供程序集成,以便可以帮助保护单页面应用中的各个视图。Adal.js integrates with AngularJS route and HTTP providers, so you can help secure individual views in your single-page app.

  1. App/Scripts/app.js 中引入 adal.js 模块:In App/Scripts/app.js, bring in the adal.js module:

    angular.module('todoApp', ['ngRoute','AdalAngular'])
    .config(['$routeProvider','$httpProvider', 'adalAuthenticationServiceProvider',
     function ($routeProvider, $httpProvider, adalProvider) {
    ...
    
  2. 使用应用程序注册的配置值初始化 adalProvider(同样在 App/Scripts/app.js 中):Initialize adalProvider by using the configuration values of your application registration, also in App/Scripts/app.js:

    adalProvider.init(
      {
          instance: 'https://login.partner.microsoftonline.cn/',
          tenant: 'Enter your tenant name here e.g. contoso.partner.onmschina.cn',
          clientId: 'Enter your client ID here e.g. e9a5a8b6-8af7-4719-9821-0deef255f68e',
          extraQueryParameter: 'nux=1',
          //cacheLocation: 'localStorage', // enable this for IE, as sessionStorage does not work for localhost.
      },
      $httpProvider
    );
    
  3. 只需使用一行代码,即可帮助保护应用中的 TodoList 视图:requireADLoginHelp secure the TodoList view in the app by using only one line of code: requireADLogin.

    ...
    }).when("/TodoList", {
            controller: "todoListCtrl",
            templateUrl: "/App/Views/TodoList.html",
            requireADLogin: true,
    ...
    

摘要Summary

现在,已获得一个安全的单页面应用,它可以让用户登录,并可向其后端 API 发出受持有者令牌保护的请求。You now have a secure single-page app that can sign in users and issue bearer-token-protected requests to its back-end API. 用户单击 TodoList 链接时,adal.js 会根据需要自动重定向到 Azure AD 以进行登录。When a user clicks the TodoList link, adal.js will automatically redirect to Azure AD for sign-in if necessary. 此外,adal.js 会自动将访问令牌附加到已发送至应用后端的任何 Ajax 请求。In addition, adal.js will automatically attach an access token to any Ajax requests that are sent to the app's back end.

前面的步骤仅是使用 adal.js 生成单页面应用的最低必要条件。The preceding steps are the bare minimum necessary to build a single-page app by using adal.js. 但一些其他功能在单页面应用中很有用:But a few other features are useful in single-page app:

  • 若要显式发出登录和注销请求,可以在调用 adal.js 的控制器中定义函数。To explicitly issue sign-in and sign-out requests, you can define functions in your controllers that invoke adal.js. App/Scripts/homeCtrl.js中:In App/Scripts/homeCtrl.js:

    ...
    $scope.login = function () {
        adalService.login();
    };
    $scope.logout = function () {
        adalService.logOut();
    };
    ...
    
  • 可能需要在应用的 UI 中显示用户信息。You might want to present user information in the app's UI. ADAL 服务已添加到 userDataCtrl 控制器,因此可在关联的视图 App/Views/UserData.html 中访问 userInfo 对象:The ADAL service has already been added to the userDataCtrl controller, so you can access the userInfo object in the associated view, App/Views/UserData.html:

    <p>{{userInfo.userName}}</p>
    <p>aud:{{userInfo.profile.aud}}</p>
    <p>iss:{{userInfo.profile.iss}}</p>
    ...
    
  • 在许多情况下,你希望知道用户是否已登录。There are many scenarios in which you'll want to know if the user is signed in or not. 也可以使用 userInfo 对象来收集此信息。You can also use the userInfo object to gather this information. 例如,在 index.html 中,可以根据身份验证状态显示“登录”或“注销”按钮:For instance, in index.html, you can show either the Login or Logout button based on authentication status:

    <li><a class="btn btn-link" ng-show="userInfo.isAuthenticated" ng-click="logout()">Logout</a></li>
    <li><a class="btn btn-link" ng-hide=" userInfo.isAuthenticated" ng-click="login()">Login</a></li>
    

集成了 Azure AD 的单页面应用可对用户进行身份验证,使用 OAuth 2.0 安全调用其后端,并获取有关用户的基本信息。Your Azure AD-integrated single-page app can authenticate users, securely call its back end by using OAuth 2.0, and get basic information about the user. 如果尚未这样做,可以在租户中填充一些用户。If you haven't already, now is the time to populate your tenant with some users. 运行待办事项列表单页面应用,并使用这些用户之一进行登录。Run your To Do List single-page app, and sign in with one of those users. 将任务添加到用户的待办事项列表、注销并重新登录。Add tasks to the user's to-do list, sign out, and sign back in.

使用 Adal.js 可以方便地将常见标识功能合并到应用程序中。Adal.js makes it easy to incorporate common identity features into your application. 它负责所有的繁琐工作:缓存管理、OAuth 协议支持、向用户显示登录 UI、刷新已过期的令牌等。It takes care of all the dirty work for you: cache management, OAuth protocol support, presenting the user with a sign-in UI, refreshing expired tokens, and more.

GitHub 中提供了已完成示例(无配置值)以供参考。For reference, the completed sample (without your configuration values) is available in GitHub.

后续步骤Next steps

现在,可以转到其他方案。You can now move on to additional scenarios.