跳到主要内容

WalletAuthenticator

WalletAuthenticator 是 DID Connect 会话中服务器端逻辑的核心类。它负责创建认证请求、签署响应以及验证从用户钱包返回的数据。它独立于任何特定的 Web 框架运行,处理所有加密操作和 JWT 管理。

要将 DID Connect 集成到 Express.js 应用程序中,请参阅 WalletHandlers 类,该类构建于 WalletAuthenticator 之上。

构造函数

new WalletAuthenticator(config)

创建 WalletAuthenticator 的一个新实例。这是为 DID Connect 设置应用程序身份和配置的入口点。

Authenticator Setup

javascript
const { WalletAuthenticator } = require('@arcblock/did-connect');
const { fromRandom } = require('@ocap/wallet');

// 应用程序的钱包
const appWallet = fromRandom().toJSON();
const chainHost = 'https://beta.abtnetwork.io/api';
const chainId = 'beta';

const auth = new WalletAuthenticator({
  wallet: appWallet,
  baseUrl: 'https://example.com',
  appInfo: {
    name: 'DID Connect Demo',
    description: 'A demo application for DID Connect',
    icon: 'https://arcblock.oss-cn-beijing.aliyuncs.com/images/wallet-round.png',
    link: 'https://example.com'
  },
  chainInfo: {
    host: chainHost,
    id: chainId,
  },
});

参数

  • wallet WalletObject | Function (required) — 应用程序的钱包实例或返回该实例的函数。此钱包用于签署与用户钱包的所有通信。
  • appInfo ApplicationInfo | Function (required) — 一个对象或函数,返回要在用户钱包中显示的应用程序基本信息(名称、描述、图标等)。
  • chainInfo ChainInfo | Function — 有关应用程序所连接的区块链的信息。可以是一个对象或返回该对象的函数。默认为 'none' 链。
  • delegator WalletObject | Function — 授权 config.wallet 代表其行事的钱包。用于委托认证流程。
  • delegation string | Function — 证明 delegator 和 wallet 之间委托关系的 JWT 令牌。
  • baseUrl string — 用于构建回调 URL 的基础 URL。通常可以从 Web 服务器上下文中的请求对象推断出来。
  • timeout number (default: 8000) — 生成声明的超时时间(毫秒)。
  • tokenKey string (default: _t_) — 用于会话令牌的查询参数键。

方法

uri()

生成一个深度链接 URL,可以渲染成二维码供 DID 钱包扫描以启动会话。

Generating a Connect URL

javascript
const connectUrl = auth.uri({
  baseUrl: 'https://example.com',
  pathname: '/api/connect/relay/auth',
  token: 'some_session_token',
  query: { userAction: 'login' },
});

// connectUrl 将类似于:
// https://abtwallet.io/i/?action=requestAuth&url=https%3A%2F%2Fexample.com%2Fapi%2Fconnect%2Frelay%2Fauth%3FuserAction%3Dlogin%26_t_%3Dsome_session_token

参数

  • params object — 包含 URI 参数的对象。
    • baseUrl string — 用于构建回调 URL 的基础 URL。
    • pathname string — 钱包回调端点的路径。
    • token string — 此认证操作的唯一会话令牌。
    • query object (default: {}) — 要在回调 URL 中保留的附加查询参数对象。

返回

  • **** string — 一个用于 DID 钱包的深度链接 URL。

sign()

签署要发送到钱包的认证请求。这个 JWT 格式的响应包含应用程序信息、链信息以及向用户请求的具体声明。

Signing an Auth Request

javascript
const authResponse = await auth.sign({
  claims: { profile: { items: ['fullName', 'email'] } }, // 请求用户的姓名和邮箱
  pathname: '/api/connect/relay/auth',
  baseUrl: 'https://example.com',
  challenge: 'random_challenge_string',
  context: { token: 'some_session_token' },
});

// authResponse 包含 { appPk, authInfo, ... }

参数

  • params object (required) — 签署认证请求的参数。
    • claims object (required) — 一个定义需要从用户钱包获取的信息的对象。详情请参见声明参考。
    • pathname string — 用于组装回调 URL 的路径名。
    • baseUrl string — 回调的基础 URL。
    • challenge string — 一个随机的质询字符串,用于防止重放攻击。
    • context object (required) — 包含会话上下文的对象。
      • token string (required) — 会话令牌。
      • userDid string — 用户的 DID。
      • userPk string — 用户的公钥。
      • sharedKey string — 用于敏感声明的应用和钱包之间的共享密钥。
      • encryptionKey string — 来自钱包的加密密钥。
    • request object — 来自 Web 服务器的原始请求对象(如果可用)。

返回

  • **** Promise<object> — 一个解析为包含已签名的 authInfo (JWT)、应用程序的公钥 appPk 以及其他相关密钥(如 agentPk 或 sharedKey)的对象的 Promise。

signResponse()

为钱包签署一个简单的最终响应,通常在操作成功或报告错误后使用。此响应可以选择性地将用户钱包重定向到一个新 URL。

Signing a Success Response

javascript
const successResponse = await auth.signResponse({
  successMessage: 'Login successful!',
  nextUrl: 'https://example.com/dashboard',
}, 'https://example.com', requestContext);

// 此响应可以发送回钱包。

参数

  • params object (required) — 响应的参数。
    • successMessage string — 成功时在钱包中显示的消息。
    • errorMessage string — 出错时在钱包中显示的消息。
    • nextUrl string — 显示消息后在钱包的 webview 中打开的 URL。
    • nextWorkflow string — 指向另一个 DID Connect 工作流的 URL,用于将多个请求链接在一起。
    • response object — 要包含在响应中的任何附加 JSON 数据。
    • cookies object — 在打开 nextUrl 之前要设置为 cookie 的键值对。
    • storages object — 在打开 nextUrl 之前要设置为 localStorage 的键值对。

返回

  • **** Promise<object> — 一个解析为包含已签名的 authInfo 和 appPk 的对象的 Promise。

verify()

验证从 DID 钱包发送的响应。它使用用户的公钥检查签名,并解码 JWT 以提取声明和其他会话信息。

Verifying a Wallet Response

javascript
try {
  const walletResponse = {
    userPk: 'user_public_key_from_wallet',
    userInfo: 'jwt_token_from_wallet',
    token: 'the_original_session_token'
  };

  const verificationResult = await auth.verify(walletResponse);

  console.log('Verification successful!');
  console.log('User DID:', verificationResult.userDid);
  console.log('Requested Claims:', verificationResult.claims);
} catch (error) {
  console.error('Verification failed:', error.message);
}

参数

  • data object (required) — 一个包含来自钱包响应的 userPk 和 userInfo (JWT) 的对象。
  • locale string (default: en) — 错误消息的区域设置。
  • enforceTimestamp boolean (default: true) — 是否强制执行 JWT 的时间戳有效性。设置为 false 可调试时间同步问题。

返回

  • **** Promise<object> — 一个解析为已解码对象的 Promise。
    • token string — 原始会话令牌。
    • userDid string — 已认证用户的 DID。
    • userPk string — 已认证用户的公钥。
    • claims array — 用户满足的声明数组。
    • challenge string — 原始质询字符串。
    • timestamp number — JWT 的颁发时间戳。

类型定义

ApplicationInfo

此对象定义了在连接会话期间在用户的 DID 钱包中向用户显示的有关您的应用程序的信息。

  • name string (required) — 您的应用程序的名称。
  • description string (required) — 您的应用程序的简要描述。
  • icon string (required) — 您的应用程序徽标的 URL。
  • link string — 指向您的应用程序主页的链接,允许用户从他们的钱包返回。
  • publisher string — 应用程序发布者的 DID。如果未提供,则自动设置为应用程序钱包的 DID。
  • path string (default: https://abtwallet.io/i/) — 钱包的深度链接 URL 前缀。

ChainInfo

此对象指定您的应用程序与之交互的区块链。

  • id string (required) — 链的 ID(例如 'beta'、'main')。对于 EVM 链,这是链 ID 号。
  • host string (required) — ArcBlock 链的 GraphQL 端点,或 EVM 链的 JSON-RPC 端点。
  • type string (default: arcblock) — 区块链的类型。可以是 'arcblock'、'ethereum' 等。

现在您已经了解了如何创建和管理认证逻辑,下一步是将其集成到 Web 服务器中。请继续阅读 WalletHandlers API 参考,了解如何将 DID Connect 端点附加到 Express.js 应用程序。