# @azure/ms-rest-nodeauth 中文文档

规范地址：https://npmcn.com/package/%40azure/ms-rest-nodeauth/

版本：3\.1\.1
npm 元数据更新时间：2026-06-08T19:45:54.947Z
中文译文更新时间：2026-11-07T13:20:26.517Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40azure/ms-rest-nodeauth
原文对照：https://npmcn.com/package/%40azure/ms-rest-nodeauth/?lang=original
项目主页：https://github.com/Azure/ms-rest-nodeauth
源码仓库：https://github.com/Azure/ms-rest-nodeauth

弃用说明：This package has been deprecated in favor of the new identity packages from \[Azure SDK for JavaScript\]\(https://github\.com/azure/azure-sdk-for-js\)\.

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：363 kB，89 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：3 个
- 首次发布：2018-11-12T22:12:38.342Z
- 最新版本发布：2021-12-15T23:50:11.341Z
- 近 30 天下载量：547544（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：33（近 12 个月 0 个）

## 中文简介

Azure 认证库在有类型定义的节点.js中.

## 安装

```sh
npm install @azure/ms-rest-nodeauth
```

也可以使用：`pnpm add @azure/ms-rest-nodeauth`、`yarn add @azure/ms-rest-nodeauth`、`bun add @azure/ms-rest-nodeauth`

## README

# 毫秒后空档 [![Build Status](https://dev.azure.com/azure-public/adx/_apis/build/status/public.Azure.ms-rest-nodeauth)](https://dev.azure.com/azure-public/adx/_build/latest?definitionId=9)

这个 `@azure/ms-rest-nodeauth` 软件包提供了不同的认证机制,意在使用一组来自 [用于 JavaScript 和 TypeScript 的 Azure SDK](https://github.com/Azure/azure-sdk-for-js)。 。 。 .

没有积极发展 `@azure/ms-rest-nodeauth` 除了关键错误修正。 请参看下表,以找到您在使用来自Azure的证书的每项服务的建议的替代办法 `@azure/ms-rest-nodeauth`。 。 。 .

| Azure服务 | 软件包 | @azure/ms-rest-nodeauth 的替代品 |
| --- | --- | --- |
| Azure 资源管理器 | 以名称开头的软件包 `@azure/arm-` | 截至2021年12月,所有针对Azure资源管理器的软件包的新主要版本将放弃对来自 `@azure/ms-rest-nodeauth`。参考 [使用@azure/身份的迁移指南](https://github.com/Azure/ms-rest-nodeauth/blob/master/migrate-to-identity-v2.md) 换句话说. |
| 应用程序透视 | @azure/ applicentinsights- query | 未计划,因为本套装将贬值,有利于 `@azure/monitor-query` (原始内容存档于2022年初). official website. |
| 应用程序透视 | @azure/逻辑分析 | 未计划,因为本套装将贬值,有利于 `@azure/monitor-query` (原始内容存档于2022年初). official website. |
| 批次 | @ azure/ 批量 | 还没有替代品 |
| 图 | @ azure/ graph | 由于这项服务将于2022年6月贬值,因此没有计划. |
| 服务家具 | @azure/服务布局 | 未规划,因为此套件没有积极开发. |
| 存储数据湖 | @ azure/ storage- datalake 页面存档备份,存于互联网档案馆 | 未规划,因为此套件没有积极开发. |

所有认证方法都支持召回和许诺。 如果在您的应用程序中它们被调用在同步方法中, 那么您也可以使用同步/等待模式 .

**使用个人账户时要考虑的事项:**

在使用个人账户时 `domain` 转让给认证方法的选项中的财产是强制性的,应当设定为租户身份。 如果不设定此属性, 认证方法创建的证书将无法访问个人账户的任何资源 。 出于同样的原因,这些方法的回放值中预期的订阅数将空出.

你可以从Azure门户网站或Azure CLI那里得到租户ID. 如果你需要接房客的话 在方案方面,遵循以下步骤:

-   在不设置域的情况下使用任何认证方法来获取证书. - 打电话 `buildTenantLists(credential)` 方法,发送同样的证书 作为第一个参数 得到所有租户列表 在您的账户.

您现在可以使用任何认证方法 并且通过租户 编号或使用 `setDomain()` 在现有的证书上修改它用来创建代币的租户的方法.

### 在代理支持下已知的问题

此软件包使用 `adal-node` 移动到 `axios` 从 `request` 作为自 npm 支持以来 http Requests since `request` 已中止。 但后来注意到 [`axios` 不支持代理人](https://github.com/axios/axios/issues/2072)编辑 `adal-node` 软件包仅需要安全变化,不会解决这个问题。 因此,我们建议使用 `https-proxy-agent` 如果您需要您的申请代理,请联系上的问题。 例如:

```
// paste this code to support proxy environment
// reference:
// https://github.com/axios/axios/issues/2072#issuecomment-567473812
const HttpsProxyAgent = require('https-proxy-agent');
const axios = require('axios')
axios.defaults.proxy = false
axios.defaults.httpsAgent = new HttpsProxyAgent('http://MY_PROXY:8888')
```

### 示例

### 基于用户名/ 密码的登录

```typescript
import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";

const username = process.env["AZURE_USERNAME"];
const password = process.env["AZURE_PASSWORD"];

msRestNodeAuth
  .loginWithUsernamePasswordWithAuthResponse(username, password)
  .then((authres) => {
    console.dir(authres, { depth: null });
  })
  .catch((err) => {
    console.log(err);
  });
```

### 主要和秘密登录

```typescript
import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";

const clientId = process.env["CLIENT_ID"];
const secret = process.env["APPLICATION_SECRET"];
const tenantId = process.env["DOMAIN"];

msRestNodeAuth
  .loginWithServicePrincipalSecretWithAuthResponse(clientId, secret, tenantId)
  .then((authres) => {
    console.dir(authres, { depth: null });
  })
  .catch((err) => {
    console.log(err);
  });
```

#### 通过提供 ABSOLUTE 文件路径到.pem 文件,服务主和基于证书的登录

```typescript
import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";

const clientId = process.env["CLIENT_ID"];
const tenantId = process.env["DOMAIN"];

msRestNodeAuth
  .loginWithServicePrincipalCertificateWithAuthResponse(clientId, "/Users/user1/foo.pem", tenantId)
  .then((authres) => {
    console.dir(authres, { depth: null });
  })
  .catch((err) => {
    console.log(err);
  });
```

#### 通过提供证书和私人密钥( . pem 文件的内容) 提供基于证书的原始登录

```typescript
import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";

const clientId = process.env["CLIENT_ID"];
const tenantId = process.env["DOMAIN"];
const certificate = `
-----BEGIN PRIVATE KEY-----
xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxx
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
yyyyyyyyyyyyyyyyy
yyyyyyyyyyyyyyyyy
-----END CERTIFICATE-----
`;

msRestNodeAuth
  .loginWithServicePrincipalCertificateWithAuthResponse(clientId, certificate, tenantId)
  .then((authres) => {
    console.dir(authres, { depth: null });
  })
  .catch((err) => {
    console.log(err);
  });
```

### 交互式/设备编码流程登录

```typescript
import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";

msRestNodeAuth
  .interactiveLoginWithAuthResponse()
  .then((authres) => {
    console.dir(authres, { depth: null });
  })
  .catch((err) => {
    console.log(err);
  });
```

### 从磁盘上的认证文件进行服务- 主要认证

在使用此方法之前, 请安装 az cli [https://github.com/Azure/azure-cli/放行. 星洲网](https://github.com/Azure/azure-cli/releases)。 。 。 . 然后执行 `az ad sp create-for-rbac --sdk-auth > ${yourFilename.json}`。 。 。 .

如果您想要为不同的云/环境创建sp, 请执行 :

1.  az 云表单
    
2.  az 云设置 -n
    
3.  az ad sp 创建- for-rbac -- sdk-auth > auth.json // 创建 sp 与 **隐藏**。 。 。 . 或
    
    az ad sp 为- rbac -- create- cert -- sdk- auth > auth.json // 创建 sp 与 **证书**。 。 。 . 如果服务主已创建, 那么登录服务主信息 :
    
4.  az 登录 - service-principal -u `<clientId>` - p `<clientSecret>` - 号 `<tenantId>`
    
5.  az 账户显示 -- sdk- auth > auth.json
    

```typescript
import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";

const options: msRestNodeAuth.LoginWithAuthFileOptions = {
  filePath: "<file path to auth file>"
};
msRestNodeAuth
  .loginWithAuthFileWithAuthResponse(options)
  .then((authRes) => {
    console.log(authRes);
    console.log(process.env["AZURE_SUBSCRIPTION_ID"]);
  })
  .catch((err) => {
    console.log(err);
  });
```

### MSI(Managed Service Identity)基于Azure创建的虚拟机的登录.

以下代码既适用于系统管理的身份,也适用于用户指定的身份。 你可以离开 `options` 如果您想要使用系统管理的身份, 则为空 。 如果您想要使用用户指定管理的身份, 您至少必须提供 `clientId` 在选项中。 如果您的 VM 有多个用户指定管理的身份, 您必须包含 `objectId` 财务报告和审定财务报表 `identityId` 在选项中也.

```typescript
import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";

const options: msRestNodeAuth.MSIVmOptions = {
  // The objectId of the managed identity you would like the token for.
  // Required, if your VM has multiple user-assigned managed identities.
  //
  //     objectId: "your-managed-identity-object-id",
  //
  // The clientId of the managed identity you would like the token for.
  // Required, if your VM has any user-assigned managed identity.
  //
  //     clientId: "your-managed-identity-client-id",
  //
  // The `Azure Resource ID` of the managed identity you would like the token for.
  // Required, if your VM has multiple user-assigned managed identities.
  //
  //     identityId: "your-managed-identity-identity-id",
  //
};

msRestNodeAuth
  .loginWithVmMSI(options)
  .then((msiTokenRes) => {
    console.log(msiTokenRes);
  })
  .catch((err) => {
    console.log(err);
  });
```

### 基于 AppService 或 Azure 函数的 MSI( 管理服务身份) 登录.

以下代码既适用于系统管理的身份,也适用于用户指定的身份。 你可以离开 `options` 如果您想要使用系统管理的身份, 则为空 。 如果您想要使用用户指定管理的身份, 您至少必须提供 `clientId` 在选项中.

```typescript
import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";

const options: msRestNodeAuth.MSIAppServiceOptions = {
  // The clientId of the managed identity you would like the token for.
  // Required, if your app service has user-assigned managed identities.
  //
  //     clientId: "your-managed-identity-client-id"
  //
};

msRestNodeAuth
  .loginWithAppServiceMSI(options)
  .then((msiTokenRes) => {
    console.log(msiTokenRes);
  })
  .catch((err) => {
    console.log(err);
  });
```

### 通过Azure CLI获取证书.

**先决条件**

-   **安装 azure- cli**。更多信息见 [这里](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)。 。 。 .
-   **登录通过 `az login`**
-   详细样本 [这里](https://npmcn.com/package/%40azure/ms-rest-nodeauth/samples/getCredentialsFromAzureCli.ts)。 。 。 .

```typescript
import { AzureCliCredentials } from "@azure/ms-rest-nodeauth";
import { ServiceClient, RequestPrepareOptions } from "@azure/ms-rest-js";

async function main(): Promise<void> {
  try {
    // Please make sure you have logged in via Azure CLI `az login` before executing this script.
    const creds = await AzureCliCredentials.create();
    const client = new ServiceClient(creds);
    console.log(
      ">>> Subscription associated with the access token: '%s'.",
      creds.tokenInfo.subscription
    );

    const request: RequestPrepareOptions = {
      url: getUrl(creds.subscriptionInfo.id),
      method: "GET"
    };
    console.log(">>> Request url: '%s'.", request.url);

    const res = await client.sendRequest(request);
    console.log(
      "List of resource groups from subscriptionId '%s': \n%O",
      creds.subscriptionInfo.id,
      res.parsedBody
    );

    // Let us change the subscriptionId, which should trigger refreshing the access token.
    const subscriptions = await AzureCliCredentials.listAllSubscriptions();
    creds.subscriptionInfo = subscriptions[1];

    console.log(
      ">>> The new subscription Id associated with the credential object is: '%s'.",
      creds.subscriptionInfo.id
    );
    request.url = getUrl(creds.subscriptionInfo.id);
    console.log(">>> Request url: '%s'.", request.url);

    const res2 = await client.sendRequest(request);
    console.log(
      "List of resource groups from subscriptionId '%s': \n%O",
      creds.subscriptionInfo.id,
      res2.parsedBody
    );

    console.log(
      ">>> Subscription associated with the access token: '%s'.",
      creds.tokenInfo.subscription
    );
  } catch (err) {
    console.log(err);
  }
}

function getUrl(subscriptionId: string): string {
  return `https://management.azure.com/subscriptions/${subscriptionId}/resourcegroups?api-version=2018-05-01`;
}

main();
```

### 正在用已存在的符号认证

如果您已经从另一个来源获取了有效的 Azure Active Directory 令牌, 您可以使用它来使用 Azure SDK 库进行认证 :

```js
const { HttpHeaders } = require("@azure/ms-rest-js");

function getCredentialForToken(accessToken) {
  return {
    signRequest: (request) => {
      if (!request.headers) request.headers = new HttpHeaders();
      request.headers.set("Authorization", `Bearer ${accessToken}`);
      return Promise.resolve(request);
    }
  };
}

const creds = getCredentialForToken("your existing token");
```

### 捐款

该项目欢迎各方的贡献和建议。 大多数捐款要求您同意 撰稿人许可协议(CLA)宣布,你有权并且实际上确实给了我们 有权使用您的贡献。 详情请访问 [https://cla.microsoft.com (中文(简体) )](https://cla.microsoft.com/)。 。 。 .

当您提交拉动请求时, CLA 机器人会自动确定您是否需要提供 a CLA并适当装饰公关(例如标签、评论)。 只要听从指示 由机器人提供。 你只需要用我们的CLA 一次就能完成.

该项目通过了 [Microsoft 开源行为守则](https://opensource.microsoft.com/codeofconduct/)。 。 。 . 更多信息见 [《行为守则》](https://opensource.microsoft.com/codeofconduct/faq/) 或者说 联系人 [打开码@ microsoft.com](mailto:opencode@microsoft.com) 并附上任何其他问题或评论.

## 常见问题

### @azure/ms-rest-nodeauth 是什么？

Azure 认证库在有类型定义的节点\.js中\.注意：该包已被作者标记为弃用——This package has been deprecated in favor of the new identity packages from \[Azure SDK for JavaScript\]\(https://github\.com/azure/azure-sdk-for-js\)\.

### 如何安装 @azure/ms-rest-nodeauth？

在项目目录运行 npm install @azure/ms-rest-nodeauth，或使用 pnpm add / yarn add / bun add。

### @azure/ms-rest-nodeauth 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @azure/ms-rest-nodeauth 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @azure/ms-rest-nodeauth 可以商用吗？

@azure/ms-rest-nodeauth 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @azure/ms-rest-nodeauth 的下载量有多少？

根据 npm 官方下载统计，@azure/ms-rest-nodeauth 在 2026/10/08 – 2026/11/06 这 30 天内被下载 547,544 次，日均约 18,251 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @azure/ms-rest-nodeauth 还在维护吗？

最新版本 3\.1\.1 发布于 2021/12/16（4 年前）；至今共发布 33 个版本，其中过去 12 个月发布了 0 个；首次发布于 2018/11/13。作者已将其标记为弃用，新项目建议寻找替代方案。

