通过


Microsoft Node 的身份验证扩展

Microsoft Node 身份验证扩展使开发人员能够对磁盘执行跨平台令牌缓存序列化和持久性。 它为 Node 的 Microsoft 身份验证库 (MSAL) 提供额外支持。

默认情况下,Node 的 MSAL 支持内存中缓存,并提供 ICachePlugin 接口来执行缓存序列化,但不提供将令牌缓存存储到磁盘的默认方法。 Node 的Microsoft身份验证扩展是跨不同平台将缓存保存到磁盘的默认实现。

Node 的Microsoft身份验证扩展支持以下平台:

  • Windows - 数据保护 API(DPAPI)用于保护。
  • Mac - 使用 Mac 密钥链。
  • Linux - 使用 LibSecret 来存储到“机密服务”。

安装

msal-node-extensions 包在节点包管理器(NPM)上可用。

npm i @azure/msal-node-extensions --save

配置令牌缓存

下面是使用 Node Microsoft 身份验证扩展配置令牌缓存的代码示例。

const {
  DataProtectionScope,
  Environment,
  PersistenceCreator,
  PersistenceCachePlugin,
} = require("@azure/msal-node-extensions");

// You can use the helper functions provided through the Environment class to construct your cache path
// The helper functions provide consistent implementations across Windows, Mac and Linux.
const cachePath = path.join(Environment.getUserRootDirectory(), "./cache.json");

const persistenceConfiguration = {
  cachePath,
  dataProtectionScope: DataProtectionScope.CurrentUser,
  serviceName: "<SERVICE-NAME>",
  accountName: "<ACCOUNT-NAME>",
  usePlaintextFileOnLinux: false,
};

// The PersistenceCreator obfuscates a lot of the complexity by doing the following actions for you :-
// 1. Detects the environment the application is running on and initializes the right persistence instance for the environment.
// 2. Performs persistence validation for you.
// 3. Performs any fallbacks if necessary.
PersistenceCreator.createPersistence(persistenceConfiguration).then(
  async (persistence) => {
    const publicClientConfig = {
      auth: {
        clientId: "<CLIENT-ID>",
        authority: "<AUTHORITY>",
      },

      // This hooks up the cross-platform cache into MSAL
      cache: {
        cachePlugin: new PersistenceCachePlugin(persistence),
      },
    };

    const pca = new msal.PublicClientApplication(publicClientConfig);

    // Use the public client application as required...
  }
);

下表提供了持久性配置的所有参数的说明。

字段名称 DESCRIPTION 以下操作系统所需
缓存路径 供库用于同步读取和写入的锁定文件的路径 Windows、Mac 和 Linux
数据保护范围 指定Windows当前用户或本地计算机上的数据保护范围。 Windows操作系统
服务名称 指定要在 Mac 和/或 Linux 上使用的服务名称 Mac 和 Linux
账户名称 指定要在 Mac 和/或 Linux 上使用的帐户名称 Mac 和 Linux
usePlaintextFileOnLinux 当 LibSecret 失败时在 linux 上默认设置为纯文本的标志。 默认为 false Linux

后续步骤

有关Microsoft Node 和 MSAL Node 的身份验证扩展的详细信息,请参阅: