@arcblock/did-auth

中文文档
1.21.1发布于 2025/08/05Apache-2.0TypeScriptCommonJS近 30 天下载 5349

Helper function to setup DID authentication support on a node.js web server

原始使用文档
文档目录8 节
  1. Overview
  2. Install
  3. Usage
  4. Basic Usage
  5. Multiple Claims
  6. Dynamic Claims
  7. Lifecycle Callbacks
  8. Claims

did-auth

styled with prettier docs Gitter

Overview

This library is implemented according to ABT-DID-Protocol, aiming to make it easier for developers to handle customized DID Connect Sessions in Node.js applications, and should always be used together with DID Connect UX package, if you are composing a blocklet, you may find the wrapped implementation in Blocklet SDK more useful.

Within a typical DID Connect Session, the application may request user to sign a transaction or provide some information, such as:

  • Provide a user profile, which may contain name, email
  • Prove ownership of a NFT
  • Prove ownership of a passport

The following diagram demonstrates how a typical DID Connect Session works:

Claim is the key concept in DID Connect Session, its used by the application to send specification of required info to finish the session. A claim is identified by type, and defined with a set of properties. Checkout the claim section for more information.

Install

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

Usage

Basic Usage

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/[email protected]',
    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);
    }
  },
});

Then your application backend is ready to handle DID Connect Session that request and accept profile from user. For frontend integration please checkout DID Connect UX.

Multiple Claims

You can request multiple claims in a single DID Connect Session:

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
  },
});

If you want to provide multiple claims of the same type:

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
  },
});

Dynamic Claims

By returning a claims object from onConnect callback, you can provide dynamic claims for the DID Connect Session.

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
  },
});

Lifecycle Callbacks

Following callbacks are supported during the lifecycle of a DID-Connect session.

  • onStart({ req, challenge, didwallet, extraParams, updateSession }): optional, called when a new session starts, can be async, return values from this callback will be returned to and available from browser, error thrown from onStart will halt the session.
  • onConnect({ req, challenge, userDid, userPk, extraParams, updateSession }): optional, when wallet has selected userDid and userPk, you can return dynamic claims here, or do some permission check, error thrown from onConnect will halt the session.
  • onDecline({ req, challenge, userDid, userPk, extraParams, updateSession }): optional, when wallet has rejected dapp request.
  • onAuth({ req, challenge, claims, userDid, userPk, extraParams, updateSession }): required, when wallet has approved dapp request, and submitted info will be available in claims, which is a list of the dapp requested info.
  • onComplete({ req, userDid, userPk, extraParams, updateSession }): optional, when the did connect session has completed.
  • onExpire({ extraParams }): optional, when the did connect session has expired.
  • onError({ err, extraParams }): optional, when the did connect session encountered some error, default to console.error.

Most commonly used callbacks are onConnect and onAuth.

Developer should always attach an onAuth callback for a DID Connect session handler. And put the business logic once user has approved and submitted the requested info in the callback.

Sometimes, developer may want to pass some information to the session storage, such as a transaction hash or login token, so that the browser can fetch for later use, developer can achieve this by call updateSession from onAuth. eg,

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);
  },
});

Claims

A claim specifies what kind of information the application can request user to provide. specifications for each claim are defined here, complete claim request and response specification can be found in the ABT DID Protocol.

版本与发布记录

@arcblock/did-auth 共发布 702 个版本,首次发布于 2019/03/27;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.21.1latest2025/08/051.3 年前
1.21.02025/07/161.3 年前
1.20.162025/07/141.3 年前
1.20.152025/06/271.4 年前
1.20.142025/06/061.4 年前
1.20.132025/06/051.4 年前

其他发布通道:next → 1.18.40-beta.6,beta → 1.18.117-beta.1。

关于 @arcblock/did-auth 的常见问题

@arcblock/did-auth 是什么?

Helper function to setup DID authentication support on a node.js web server

如何安装 @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 和提交记录判断。