通过


你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Azure Identity Plugin for Token Cache Persistence

该包为 JavaScript 的 Azure Identity 库(@azure/identity)提供了一个插件,支持持久令牌缓存。 令牌缓存持久性允许内置的令牌缓存通过本地操作系统提供的安全存储系统跨会话持久化。

源代码 | Samples

入门

先决条件

安装软件包

该软件包设计用于与 Azure Identity for JavaScript 配合使用。 使用 @azure/identity安装 npm 和此包:

$ npm install --save @azure/identity
$ npm install --save @azure/identity-cache-persistence

支持的环境

Azure Identity 的 JavaScript 插件支持从 v12 起稳定(偶数编号)Node.js 版本。 虽然这些插件可能在其他 Node 版本中运行,但不保证支持。 @azure/identity-cache-persistence 不支持浏览器环境

重要概念

如果你是第一次使用 @azure/identity 或 Microsoft Entra ID,建议你先阅读使用 @azure/identity 与 Microsoft Entra ID。 本文档将帮助您更深入地理解该平台以及如何正确配置您的 Azure 账户。

Azure Identity Plugins

@azure/identity 版本 2.0.0 起,适用于 JavaScript 的标识客户端库包括插件 API。 此包(@azure/identity-cache-persistence)将从 useIdentityPlugin 包中将插件对象作为参数传递给顶级 @azure/identity 函数。 在您的程序中启用令牌缓存持久化,具体如下:

import { useIdentityPlugin } from "@azure/identity";
import { cachePersistencePlugin } from "@azure/identity-cache-persistence";

useIdentityPlugin(cachePersistencePlugin);

调用 useIdentityPlugin后,持久令牌缓存插件注册到 @azure/identity 包中,并将在所有支持持久令牌缓存的凭证上可用(即其构造函数中包含 tokenCachePersistenceOptions 的 )。

示例

插件注册后,你可以通过将属性设置为 的 true 传递tokenCachePersistenceOptionsenabled给凭证构造器来实现令牌缓存持久化。 在以下示例中,我们使用了 , DeviceCodeCredential因为其令牌的持久缓存允许你跳过互动设备代码认证流程,前提是有缓存令牌可用。

import { DeviceCodeCredential } from "@azure/identity";

const credential = new DeviceCodeCredential({
  tokenCachePersistenceOptions: {
    enabled: true,
  },
});

// We'll use the Microsoft Graph scope as an example
const scope = "https://graph.microsoft.com/.default";

// Print out part of the access token
console.log((await credential.getToken(scope)).token.substring(0, 10), "...");

故障排除

伐木业

启用日志记录可能有助于发现有关故障的有用信息。 若要查看 HTTP 请求和响应的日志,请将 AZURE_LOG_LEVEL 环境变量设置为 info。 或者,可以通过在 setLogLevel中调用 @azure/logger 在运行时启用日志记录:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

后续步骤

提供反馈

如果你遇到漏洞或有建议,请open a issue

Contributing

如果你想为本库贡献内容,请阅读 贡献指南,了解更多关于如何构建和测试代码的信息。