快速入门:在 JavaScript SPA 中登录用户并获得访问令牌Quickstart: Sign in users and get an access token in a JavaScript SPA

在本快速入门中,你将使用代码示例了解 JavaScript 单页应用程序 (SPA) 如何登录工作帐户和学校帐户的用户。In this quickstart, you use a code sample to learn how a JavaScript single-page application (SPA) can sign in users of work accounts, and school accounts. JavaScript SPA 还可以获取用于调用 Microsoft Graph API 或任何 Web API 的访问令牌。A JavaScript SPA can also get an access token to call the Microsoft Graph API or any web API. (有关说明,请参阅示例工作原理。)(See How the sample works for an illustration.)

先决条件Prerequisites

注册并下载快速入门应用程序Register and download your quickstart application

若要启动快速入门应用程序,请使用以下选项之一。To start your quickstart application, use either of the following options.

选项 1(快速):注册并自动配置应用,然后下载代码示例Option 1 (Express): Register and auto configure your app and then download your code sample

  1. 使用工作或学校帐户登录到 Azure 门户Sign in to the Azure portal by using a work or school account.
  2. 如果你的帐户有权访问多个租户,请在右上角选择该帐户,然后将门户会话设置为要使用的 Azure Active Directory (Azure AD) 租户。If your account gives you access to more than one tenant, select the account at the top right, and then set your portal session to the Azure Active Directory (Azure AD) tenant you want to use.
  3. 转到新的 Azure 门户 - 应用注册窗格。Go to the new Azure portal - App registrations pane.
  4. 输入应用程序的名称。Enter a name for your application.
  5. 在“支持的帐户类型”下,选择“任何组织目录中的帐户”。 Under Supported account types, select Accounts in any organizational directory.
  6. 选择“注册”。Select Register.
  7. 遵照说明下载内容,系统会自动配置新应用程序。Follow the instructions to download and automatically configure your new application.

选项 2(手动):注册并手动配置应用程序和代码示例Option 2 (Manual): Register and manually configure your application and code sample

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

  1. 使用工作或学校帐户登录到 Azure 门户Sign in to the Azure portal by using a work or school account.

  2. 如果你的帐户有权访问多个租户,请在右上角选择该帐户,然后将门户会话设置为要使用的 Azure AD 租户。If your account gives you access to more than one tenant, select your account at the top right, and then set your portal session to the Azure AD tenant you want to use.

  3. 转到面向开发人员的 Microsoft 标识平台的应用注册页。Go to the Microsoft identity platform for developers App registrations page.

  4. 选择“新注册”。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. 选择“注册”。Select Register. 在应用的“概述”页上,记下“应用程序(客户端) ID”值,供稍后使用 。On the app Overview page, note the Application (client) ID value for later use.

  8. 本快速入门要求启用隐式授权流This quickstart requires the Implicit grant flow to be enabled. 在已注册的应用程序的左窗格中,选择“身份验证”。In the left pane of the registered application, select Authentication.

  9. 在“平台配置”下,选择“添加平台”。 Under Platform Configurations, select Add a platform. 左侧将打开一个面板。A panel opens on the left. 在此面板中选择“Web 应用程序”区域。There, select the Web Applications region.

  10. 在左侧将“重定向 URI”值设置为 http://localhost:3000/Still on the left, set the Redirect URI value to http://localhost:3000/. 然后选择“访问令牌”和“ID 令牌”。 Then, select Access Token and ID Token.

  11. 选择“配置” 。Select Configure.

步骤 1:在 Azure 门户中配置应用程序Step 1: Configure your application in the Azure portal

为使本快速入门中的代码示例正常运行,需将 redirectUri 添加为 http://localhost:3000/ 并启用“隐式授权”。To make the code sample in this quickstart work, you need to add a redirectUri as http://localhost:3000/ and enable Implicit grant.

已配置 应用程序已使用这些属性进行配置。Already configured Your application is configured with these attributes.

步骤 2:下载项目Step 2: Download the project

若要使用 Node.js 在 Web 服务器中运行项目,请下载核心项目文件To run the project with a web server by using Node.js, download the core project files.

使用 Node.js 在 Web 服务器中运行项目Run the project with a web server by using Node.js

步骤 3:配置 JavaScript 应用Step 3: Configure your JavaScript app

在 JavaScriptSPA 文件夹中,编辑 authConfig.js,并在 msalConfig 下设置 clientIDauthorityredirectUri 值。In the JavaScriptSPA folder, edit authConfig.js, and set the clientID, authority and redirectUri values under msalConfig.


 // Config object to be passed to Msal on creation
 const msalConfig = {
   auth: {
     clientId: "Enter_the_Application_Id_Here",
     authority: "Enter_the_Cloud_Instance_Id_Here/Enter_the_Tenant_Info_Here",
     redirectUri: "Enter_the_Redirect_Uri_Here",
   },
   cache: {
     cacheLocation: "sessionStorage", // This configures where your cache will be stored
     storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
   }
 };

备注

Enter_the_Supported_Account_Info_Here

其中:Where:

  • <Enter_the_Application_Id_Here> 是所注册应用程序的应用程序(客户端)ID。<Enter_the_Application_Id_Here> is the Application (client) ID for the application you registered.
  • <Enter_the_Cloud_Instance_Id_Here> 是 Azure 云的实例。<Enter_the_Cloud_Instance_Id_Here> is the instance of the Azure cloud. 对于国家云(例如“中国”云),请参阅国家云For national clouds (for example, China), see National clouds.
  • <Enter_the_Tenant_info_here> 设置为以下选项之一:<Enter_the_Tenant_info_here> is set to one of the following options:
    • 如果应用程序支持“此组织目录中的帐户”,请将此值替换为“租户 ID”或“租户名称”(例如,contoso.microsoft.com)。If your application supports accounts in this organizational directory, replace this value with the Tenant ID or Tenant name (for example, contoso.microsoft.com).
    • 如果应用程序支持“任何组织目录中的帐户”,请将此值替换为 organizationsIf your application supports accounts in any organizational directory, replace this value with organizations.
    • 如果应用程序支持“任何组织目录中的帐户”,请将此值替换为“common”If your application supports accounts in any organizational directory, replace this value with common.

提示

若要查找“应用程序(客户端) ID”、“目录(租户) ID”和“支持的帐户类型”的值,请转到 Azure 门户中应用的“概述”页。 To find the values of Application (client) ID, Directory (tenant) ID, and Supported account types, go to the app's Overview page in the Azure portal.

步骤 3:应用已配置并可以运行Step 3: Your app is configured and ready to run

我们已经为项目配置了应用属性的值。We have configured your project with values of your app's properties.

然后,仍在同一文件夹中,编辑 graphConfig.js 文件,以便为 apiConfig 对象设置 graphMeEndpointgraphMeEndpointThen, still in the same folder, edit graphConfig.js file to set the graphMeEndpoint and graphMeEndpoint for the apiConfig object.

  // Add here the endpoints for MS Graph API services you would like to use.
  const graphConfig = {
    graphMeEndpoint: "Enter_the_Graph_Endpoint_Here/v1.0/me",
    graphMailEndpoint: "Enter_the_Graph_Endpoint_Here/v1.0/me/messages"
  };

  // Add here scopes for access token to be used at MS Graph API endpoints.
  const tokenRequest = {
      scopes: ["Mail.Read"]
  };

其中:Where:

  • <Enter_the_Graph_Endpoint_Here> 是将针对其进行 API 调用的终结点。<Enter_the_Graph_Endpoint_Here> is the endpoint that API calls will be made against. 对于主要或全局 Microsoft Graph API 服务,只需输入 https://microsoftgraph.chinacloudapi.cnFor the main or global Microsoft Graph API service, simply enter https://microsoftgraph.chinacloudapi.cn. 有关详细信息,请参阅国家云部署For more information, see National cloud deployment

步骤 4:运行项目Step 4: Run the project

使用 Node.js 在 Web 服务器中运行项目:Run the project with a web server by using Node.js:

  1. 若要启动服务器,请从项目目录运行以下命令:To start the server, run the following command from the project directory:

    npm install
    npm start
    
  2. 打开 Web 浏览器并转到 http://localhost:3000/Open a web browser and go to http://localhost:3000/.

  3. 选择“登录”开始登录,然后调用 Microsoft Graph API。Select Sign In to start the sign-in, and then call Microsoft Graph API.

在浏览器加载应用程序后,选择“登录”。After the browser loads the application, select Sign In. 首次登录时,系统会提示你同意允许应用程序访问你的个人资料并登录。The first time that you sign in, you're prompted to provide your consent to allow the application to access your profile and to sign you in. 成功登录后,你的用户个人资料信息应会显示在页面上。After you're signed in successfully, your user profile information should be displayed on the page.

详细信息More information

示例工作原理How the sample works

示例 JavaScript SPA 的工作原理:1.

msal.jsmsal.js

MSAL 库会将登录用户,并请求用于访问受 Microsoft 标识平台保护的 API 的令牌。The MSAL library signs in users and requests the tokens that are used to access an API that's protected by Microsoft identity platform. 快速入门 index.html 文件包含对该库的引用:The quickstart index.html file contains a reference to the library:

<script type="text/javascript" src="https://alcdn.msftauth.net/lib/1.2.1/js/msal.js" integrity="sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP" crossorigin="anonymous"></script>

提示

可将上述版本替换为 MSAL.js 版本中列出的最新发布版本。You can replace the preceding version with the latest released version under MSAL.js releases.

另外,如果已安装 Node.js,则可通过 Node.js 包管理器 (npm) 下载最新版本:Alternatively, if you have Node.js installed, you can download the latest version through Node.js Package Manager (npm):

npm install msal

MSAL 初始化MSAL initialization

快速入门代码还演示了如何初始化 MSAL 库:The quickstart code also shows how to initialize the MSAL library:

  // Config object to be passed to Msal on creation
  const msalConfig = {
    auth: {
      clientId: "75d84e7a-40bx-f0a2-91b9-0c82d4c556aa", // this is a fake id
      authority: "https://login.partner.microsoftonline.cn/common",
      redirectUri: "http://localhost:3000/",
    },
    cache: {
      cacheLocation: "sessionStorage", // This configures where your cache will be stored
      storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
    }
  };

const myMSALObj = new Msal.UserAgentApplication(msalConfig);
WhereWhere 说明Description
clientId 在 Azure 门户中注册的应用程序的应用程序 IDThe application ID of the application that's registered in the Azure portal.
authority (可选)支持帐户类型的颁发机构 URL,如前面的配置部分所述。(Optional) The authority URL that supports account types, as described previously in the configuration section. 默认颁发机构为 https://login.partner.microsoftonline.cn/commonThe default authority is https://login.partner.microsoftonline.cn/common.
redirectUri 应用程序注册配置的答复/redirectUri。The application registration's configured reply/redirectUri. 在本例中为 http://localhost:3000/In this case, http://localhost:3000/.
cacheLocation (可选)针对身份验证状态设置浏览器存储。(Optional) Sets the browser storage for the auth state. 默认为 sessionStorage。The default is sessionStorage.
storeAuthStateInCookie (可选)用于存储身份验证请求状态的库,验证浏览器 Cookie 中的身份验证流时需要该状态。(Optional) The library that stores the authentication request state that's required for validation of the authentication flows in the browser cookies. 此 Cookie 是针对 IE 和 Edge 浏览器设置的,目的是缓解某些已知问题This cookie is set for IE and Edge browsers to mitigate certain known issues.

有关可用的可配置选项的详细信息,请阅读初始化客户端应用程序For more information about available configurable options, see Initialize client applications.

用户登录Sign in users

以下代码片段演示如何进行用户登录:The following code snippet shows how to sign in users:

// Add scopes for the id token to be used at Microsoft identity platform endpoints.
const loginRequest = {
    scopes: ["openid", "profile", "https://microsoftgraph.chinacloudapi.cn/User.Read"],
};

myMSALObj.loginPopup(loginRequest)
    .then((loginResponse) => {
    //Login Success callback code here
}).catch(function (error) {
    console.log(error);
});
WhereWhere 说明Description
scopes (可选)包含在登录时为了获得用户许可而请求的范围。(Optional) Contains scopes that are being requested for user consent at sign-in time. 例如:["https://microsoftgraph.chinacloudapi.cn/user.read"](针对 Microsoft Graph)或 [ "<Application ID URL>/scope" ](针对自定义 Web API,即 api://<Application ID>/access_as_user)。For example, ["https://microsoftgraph.chinacloudapi.cn/user.read"] for Microsoft Graph or [ "<Application ID URL>/scope" ] for custom web APIs (that is, api://<Application ID>/access_as_user).

提示

另外,你可能希望使用 loginRedirect 方法将当前页重定向到登录页,而不是显示弹出窗口。Alternatively, you might want to use the loginRedirect method to redirect the current page to the sign-in page instead of a popup window.

请求令牌Request tokens

MSAL 使用三个方法来获取令牌:acquireTokenRedirectacquireTokenPopupacquireTokenSilentMSAL uses three methods to acquire tokens: acquireTokenRedirect, acquireTokenPopup, and acquireTokenSilent

以无提示方式获取用户令牌Get a user token silently

acquireTokenSilent 方法处理令牌获取和续订,无需进行任何用户交互。The acquireTokenSilent method handles token acquisitions and renewal without any user interaction. 首次执行 loginRedirectloginPopup 方法后,通常使用 acquireTokenSilent 方法获取用于访问受保护资源的令牌,以便进行后续调用。After the loginRedirect or loginPopup method is executed for the first time, acquireTokenSilent is the method commonly used to obtain tokens that are used to access protected resources for subsequent calls. 进行请求或续订令牌的调用时,以静默方式进行。Calls to request or renew tokens are made silently.


const tokenRequest = {
    scopes: ["https://microsoftgraph.chinacloudapi.cn/Mail.Read"]
};

myMSALObj.acquireTokenSilent(tokenRequest)
    .then((tokenResponse) => {
        // Callback code here
        console.log(tokenResponse.accessToken);
    }).catch((error) => {
        console.log(error);
    });
WhereWhere 说明Description
scopes 包含请求的需要在 API 的访问令牌中返回的作用域。Contains scopes being requested to be returned in the access token for API. 例如:[ "https://microsoftgraph.chinacloudapi.cn/mail.read" ](针对 Microsoft Graph)或 [ "<Application ID URL>/scope" ](针对自定义 Web API,即 api://<Application ID>/access_as_user)。For example, [ "https://microsoftgraph.chinacloudapi.cn/mail.read" ] for Microsoft Graph or [ "<Application ID URL>/scope" ] for custom web APIs (that is, api://<Application ID>/access_as_user).

以交互方式获取用户令牌Get a user token interactively

在某些情况下,需要强制用户与 Microsoft 标识平台终结点交互。There are situations where you need to force users to interact with the Microsoft identity platform endpoint. 例如:For example:

  • 由于密码已过期,用户可能需要重新输入凭据。Users might need to reenter their credentials because their password has expired.
  • 应用程序正在请求访问用户需要许可的其他资源范围。Your application is requesting access to additional resource scopes that the user needs to consent to.
  • 需要双重身份验证。Two-factor authentication is required.

建议用于大多数应用程序的常用模式是先调用 acquireTokenSilent,然后捕获异常,然后再调用 acquireTokenPopup(或 acquireTokenRedirect),以便启动交互式请求。The usual recommended pattern for most applications is to call acquireTokenSilent first, then catch the exception, and then call acquireTokenPopup (or acquireTokenRedirect) to start an interactive request.

调用 acquireTokenPopup 会显示用于登录的弹出窗口。Calling the acquireTokenPopup results in a popup window for signing in. (调用 acquireTokenRedirect 会将用户重定向到 Microsoft 标识平台终结点。)在该窗口中,为了进行交互,用户需要确认其凭证、为所需的资源提供许可,或者完成双重身份验证。(Or acquireTokenRedirect results in redirecting users to the Microsoft identity platform endpoint.) In that window, users need to interact by confirming their credentials, giving the consent to the required resource, or completing the two-factor authentication.

// Add here scopes for access token to be used at MS Graph API endpoints.
const tokenRequest = {
    scopes: ["https://microsoftgraph.chinacloudapi.cn/Mail.Read"]
};

myMSALObj.acquireTokenPopup(requestObj)
    .then((tokenResponse) => {
        // Callback code here
        console.log(tokenResponse.accessToken);
    }).catch((error) => {
        console.log(error);
    });

备注

本快速入门在 Microsoft Internet Explorer 中使用 loginRedirectacquireTokenRedirect 方法,因为 Internet Explorer 浏览器处理弹出窗口时会出现一个已知问题This quickstart uses the loginRedirect and acquireTokenRedirect methods with Microsoft Internet Explorer, because of a known issue related to the handling of popup windows by Internet Explorer.

后续步骤Next steps

有关为本快速入门生成应用程序的更详细分步指导,请参阅:For a more detailed step-by-step guide on building the application for this quickstart, see:

若要浏览 MSAL 存储库中的文档、常见问题解答、问题等,请参阅:To browse the MSAL repo for documentation, FAQ, issues, and more, see: