如何使用MSAL在JavaScript代码中获取访问令牌
JavaScript 中使用 MSAL 获取访问令牌实现方案
以下是经过验证的具体实现步骤,覆盖浏览器端单页应用(SPA)和Node.js服务端两种常用场景:
前置准备
- 首先在Azure门户完成应用注册,获取客户端ID(Client ID)、租户ID(Tenant ID)
- 配置和实际使用场景匹配的重定向URI
- 按需配置应用需要的API访问权限
依赖安装
- 浏览器端SPA场景安装:
npm install @azure/msal-browser - Node.js服务端场景安装:
npm install @azure/msal-node
1. 浏览器端(SPA)实现
1.1 初始化MSAL实例
import * as msal from "@azure/msal-browser"; // MSAL基础配置 const msalConfig = { auth: { clientId: "替换为你的应用客户端ID", authority: "https://login.microsoftonline.com/替换为你的租户ID", redirectUri: "替换为你注册时配置的重定向URI" }, cache: { cacheLocation: "sessionStorage", // 缓存位置可选localStorage storeAuthStateInCookie: false // 仅IE兼容场景开启 } }; // 实例化MSAL客户端 const msalInstance = new msal.PublicClientApplication(msalConfig);
1.2 获取访问令牌
优先走静默获取,失败后触发交互式登录,避免频繁弹窗:
// 令牌请求配置,scopes替换为你实际需要的权限范围 const tokenRequest = { scopes: ["User.Read", "Mail.Read"] }; async function getAccessToken() { // 检查当前已登录账户 const accounts = msalInstance.getAllAccounts(); if (accounts.length === 0) { // 无有效账户时先触发登录 const loginResult = await msalInstance.loginPopup(tokenRequest); return loginResult.accessToken; } try { // 静默获取已缓存的令牌,自动处理过期刷新 const silentResult = await msalInstance.acquireTokenSilent({ ...tokenRequest, account: accounts[0] }); return silentResult.accessToken; } catch (err) { // 静默获取失败时触发交互式请求 if (err.name === "InteractionRequiredAuthError") { const interactiveResult = await msalInstance.acquireTokenPopup(tokenRequest); return interactiveResult.accessToken; } throw err; } }
2. Node.js服务端实现
适用于服务到服务调用的场景,使用客户端凭证流获取令牌:
2.1 初始化MSAL实例
const msal = require('@azure/msal-node'); const msalConfig = { auth: { clientId: "替换为你的应用客户端ID", authority: "https://login.microsoftonline.com/替换为你的租户ID", clientSecret: "替换为你的应用客户端密钥" } }; // 实例化机密客户端 const confidentialClient = new msal.ConfidentialClientApplication(msalConfig);
2.2 获取访问令牌
async function getServerAccessToken() { const tokenRequest = { // 服务端权限统一使用.default后缀 scopes: ["https://graph.microsoft.com/.default"] }; const tokenResult = await confidentialClient.acquireTokenByClientCredential(tokenRequest); return tokenResult.accessToken; }
注意事项
- 不要将客户端密钥等敏感信息暴露到前端代码中,所有需要密钥的逻辑必须放在服务端处理
- 申请的权限范围要和Azure门户中配置的应用权限保持一致,避免出现权限不足错误
- MSAL内部已实现令牌自动刷新逻辑,无需手动存储、刷新令牌
- 生产环境可在初始化配置中添加日志配置,方便问题排查
内容的提问来源于stack exchange,提问作者Thuy
相关产品推荐
相关产品推荐

