快速入门:生成使用 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.


开始前,请完成这些先决条件: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 New registration.
  5. “注册应用程序”页显示后,请输入应用程序的名称。 When the Register an application page appears, enter a name for your application.
  6. 在“支持的帐户类型”下,选择“任何组织目录中的帐户”。 Under Supported account types, select Accounts in any organizational directory.
  7. 在“重定向 URI” 部分下选择 “Web”平台,并将值设置为 https://localhost:44326/(Azure AD 将令牌返回到的位置)。Select the Web platform under the Redirect URI section and set the value to https://localhost:44326/ (the location to which Azure AD will return tokens).
  8. 完成后,选择“注册” 。When finished, select Register. 在应用的“概述”页上,记下“应用程序(客户端) ID”值。 On the app Overview page, note down the Application (client) ID value.
  9. 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. 在已注册的应用程序的左侧导航窗格中,选择“身份验证”。 In the left-hand navigation pane of the registered application, select Authentication.
  10. 在“高级设置”中的“隐式授权”下,同时勾选“ID 令牌”和“访问令牌”复选框。 In Advanced settings, under Implicit grant, enable both ID tokens and Access tokens checkboxes. 由于此应用需要将用户登录并调用 API,因此需要 ID 令牌和访问令牌。ID tokens and access tokens are required since this app needs to sign in users and call an API.
  11. 选择“保存” 。Select Save.
  12. 针对应用程序,在租户中授予权限。Grant permissions across your tenant for your application. 转到“API 权限” ,在“授予同意”下选择“授予管理员同意”按钮。 Go to API permissions, and select the Grant admin consent button under Grant consent.
  13. 请选择“是”以确认。 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:

          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.
  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,


现在,已获得一个安全的单页面应用,它可以让用户登录,并可向其后端 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 () {
    $scope.logout = function () {
  • 可能需要在应用的 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:

  • 在许多情况下,你希望知道用户是否已登录。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.