# @arcblock/did-auth 中文文档

规范地址：https://npmcn.com/package/%40arcblock/did-auth/

版本：1\.21\.1
npm 元数据更新时间：2025-08-05T01:44:57.819Z
中文译文更新时间：2026-11-06T14:07:47.629Z
软件包许可：Apache-2\.0

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

原始 npm 页面：https://www.npmjs.com/package/%40arcblock/did-auth
原文对照：https://npmcn.com/package/%40arcblock/did-auth/?lang=original
项目主页：https://github.com/ArcBlock/blockchain/tree/master/did/did-auth
源码仓库：https://github.com/ArcBlock/blockchain#master

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

- 包体积（解压后）：104 kB，13 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：13 个
- 首次发布：2019-03-27T01:02:49.253Z
- 最新版本发布：2025-08-05T01:44:57.560Z
- 近 30 天下载量：5349（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：702（近 12 个月 0 个）

## 中文简介

在节点.js网络服务器上设置 DID 认证支持的帮助器功能

## 安装

```sh
npm install @arcblock/did-auth
```

也可以使用：`pnpm add @arcblock/did-auth`、`yarn add @arcblock/did-auth`、`bun add @arcblock/did-auth`

## README

![did-auth](https://www.arcblock.io/.netlify/functions/badge/?text=did-auth)

[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier) [![docs](https://img.shields.io/badge/powered%20by-arcblock-green.svg)](https://docs.arcblock.io/) [![Gitter](https://badges.gitter.im/ArcBlock/community.svg)](https://gitter.im/ArcBlock/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)

## 概览

此库按照 [ABT - DID - 协议](https://github.com/ArcBlock/abt-did-spec),旨在让开发者更容易在节点.js应用程序中处理定制的DD连接会话,并且应当始终与 [连接 UX 软件包](https://www.npmjs.com/package/@arcblock/did-connect),如果您正在编组块块,您可以在 [块状 SDK](https://www.npmjs.com/package/@blocklet/sdk) 更有用处.

在典型的DDE Connection会话中,应用程序可以要求用户签署交易或提供一些信息,例如:

-   提供用户配置文件,其中可能包含名称、电子邮件
-   证明NFT的所有权
-   证明护照的所有权

以下图表显示一个典型的 DD 连接会话是如何工作的 :

![](https://npmcn.com/package/%40arcblock/did-auth/docs/workflow.png)

`Claim` 是 DID Connect 会话中的关键概念,它被应用程序用来发送完成会话所需的信息的规格。 索赔由下列人员确定: `type`,并用一组属性定义。 查阅索赔部分的更多信息.

## 安装

```sh
npm install @arcblock/did-auth
// or
pnpm install @arcblock/did-auth
```

## 使用量

### 基本用途

```js
const SimpleStorage = require('@arcblock/did-auth-storage-nedb');
const { fromRandom } = require('@ocap/wallet');
const { WalletAuthenticator, WalletHandlers } = require('@arcblock/did-auth');

// First setup authenticator and handler factory
const wallet = fromRandom();
const authenticator = new WalletAuthenticator({
  wallet,
  baseUrl: 'http://wangshijun.natapp1.cc',
  appInfo: {
    description: 'Starter projects to develop web application on forge',
    icon: '/images/logo@2x.png',
    name: 'Forge Web Starter',
  },
  chainInfo: {
    host: 'http://did-workshop.arcblock.co:8210/api',
    id: 'forge',
  },
});

const handlers = new WalletHandlers({
  authenticator,
  tokenStorage: new SimpleStorage({ dbPath: '/tmp/test/auth.db' }),
});

// Then attach handler to express server
const express = require('express');
const app = express();

// This is required if you want to use dynamic baseUrl inference
app.set('trust proxy', true);

handlers.attach({
  action: 'profile',
  claims: {
    // This function can be async or returns a promise
    profile: () => ({
      fields: ['fullName', 'email'],
      description: 'Please provide your name and email to continue',
    }),
  },

  onAuth: async ({ userDid, claims, extraParams }) => {
    // `userDid` is the current connected did
    // `claims` contains what the user has submitted
    // `extraParams` is set from webapp when creating the session
    try {
      const profile = claims.find((x) => x.type === 'profile');
      console.info('login.success', { userDid, profile });
    } catch (err) {
      console.error('login.error', err);
    }
  },
});
```

然后您的应用程序后端可以处理 DID 连接会话, 并接受用户的配置 。 前端集成请退出 [连接 UX 是否](https://www.npmjs.com/package/@arcblock/did-connect)。 。 。 .

### 多项索赔

您可以在单个 DDE 连接会话中请求多个请求 :

```js
handlers.attach({
  action: 'multiple-claims',
  claims: {
    profile: () => ({
      fields: ['fullName', 'email'],
      description: 'Please provide your name and email to continue',
    }),
    asset: ({ userDid, extraParams }) => {
      // `userDid` is the current connected did
      // `extraParams` is set from webapp when creating the session
      return {
        description: 'Please provide a valid NFT',
        trustedIssuers: ['nft-issuer-did'],
      };
    },
  },
  onAuth: async ({ claims, userDid }) => {
    // `claims` contains both the profile and the asset claim
  },
});
```

如果您想要提供多个同类型索赔:

```js
handlers.attach({
  action: 'multiple-claims',
  claims: {
    signText: [
      'signature',
      {
        type: 'mime:text/plain',
        data: 'xxxx',
        description: 'sign the text to continue',
      },
    ],
    signHtml: [
      'signature',
      {
        type: 'mime:text/html',
        data: `<h2>This is title</h2>`,
        description: 'sign the html to continue',
      },
    ],
  },
  onAuth: async ({ claims, userDid }) => {
    // `claims` contains both the profile and the asset claim
  },
});
```

### 动态索赔

通过返回索赔对象 `onConnect` callback, 您可以为 DID 连接会话提供动态请求 .

```js
handlers.attach({
  action: 'dynamic-claims',

  // Can be async or returns a promise
  onConnect: ({ userDid }) => {
    // check userDid for some business logic
    // then return the claim object
    // you can return multiple claims here
    return {
      profile: () => ({
        fields: ['fullName', 'email'],
        description: 'Please provide your name and email to continue',
      }),
    };
  },

  onAuth: async ({ claims, userDid }) => {
    // `claims` now contains the result for the dynamic claim
  },
});
```

## 生命周期召回

在 DID- Connect 会话的生命周期中支持后续回调 .

-   `onStart({ req, challenge, didwallet, extraParams, updateSession })`: 可选的, 当新会话开始时调用, 可以是async, 从此调回的值将会返回到浏览器并可从浏览器中获取, 错误来自 `onStart` 将停止会议.
-   `onConnect({ req, challenge, userDid, userPk, extraParams, updateSession })`: 可选, 当钱包已选中时 `userDid` 财务报告和审定财务报表 `userPk`中,您可以在此返回动态索赔,或者进行一些权限检查,错误来自 `onConnect` 将停止会议.
-   `onDecline({ req, challenge, userDid, userPk, extraParams, updateSession })`: 可选, 当钱包拒绝了 dapp 请求时 .
-   `onAuth({ req, challenge, claims, userDid, userPk, extraParams, updateSession })`: 需要, 当钱包已经批准 dapp 请求, 并提交信息时, 将会在索赔中提供, 这是一份 dapp 请求的信息列表 .
-   `onComplete({ req, userDid, userPk, extraParams, updateSession })`:可选,当已连接会话完成时.
-   `onExpire({ extraParams })`: 可选, 当已连接会话已过期 .
-   `onError({ err, extraParams })`:可选,当已连接会话遇到出错时,默认为 `console.error`。 。 。 .

最常用的回调是 `onConnect` 财务报告和审定财务报表 `onAuth`。 。 。 .

开发者应始终附加一个 `onAuth` 调用 DDE 连接会话处理器 。 并在用户批准后将业务逻辑放入回调中提交所请求的信息.

有时,开发者可能想要将一些信息传递到会话存储中,例如交易散列或登录令牌,这样浏览器就可以获取供后期使用,开发者可以通过调用实现此目的 `updateSession` 从 `onAuth`{\\fn华文仿宋\\fs16\\1chd1d1d1}嗯..,

```js
handlers.attach({
  action: 'dynamic-claims',

  onAuth: ({ userDid, updateSession }) => {
    // to persist plain non-sensible info
    await updateSession({ key: 'non-sensible' });

    // to persist sensible info: that need to be encrypted
    await updateSession({ key: 'sensible' }, true);
  },
});
```

## 索偿

A 类 `claim` 指定应用程序可以要求用户提供何种信息。 确定了每项索赔的规格 [这里](https://npmcn.com/package/%40arcblock/did-auth/lib/schema/claims.js),完整的索赔要求和答复说明可见于 [ABT 协议](https://github.com/ArcBlock/ABT-DID-Protocol)。 。 。 .

## 常见问题

### @arcblock/did-auth 是什么？

在节点\.js网络服务器上设置 DID 认证支持的帮助器功能

### 如何安装 @arcblock/did-auth？

在项目目录运行 npm install @arcblock/did-auth，或使用 pnpm add / yarn add / bun add。

### @arcblock/did-auth 支持 TypeScript 吗？

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

### @arcblock/did-auth 支持 ESM 还是 CommonJS？

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

### @arcblock/did-auth 可以商用吗？

@arcblock/did-auth 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @arcblock/did-auth 的下载量有多少？

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

### @arcblock/did-auth 还在维护吗？

最新版本 1\.21\.1 发布于 2025/08/05（1\.3 年前）；至今共发布 702 个版本，其中过去 12 个月发布了 0 个；首次发布于 2019/03/27。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

