Used to check for browser translation.
用于检测浏览器翻译。
ブラウザの翻訳を検出する
API Reference

WalletAuthenticator


The WalletAuthenticator class is the core engine for handling the cryptographic operations in a DID-Auth workflow. It is responsible for creating signed authentication requests (challenges) and verifying responses from the DID Wallet. You'll use an instance of this class to manage the JWTs that secure the communication channel between your application and the user's wallet.

For a broader view of how this component fits into the overall process, see the Authentication Flow documentation.

DID WalletWalletAuthenticatorYour ApplicationDID WalletWalletAuthenticatorYour ApplicationCreate a signed JWT challengeUser scans and approvesUser's response JWTVerify user's signature and claimsauth.sign({ claims: [...] }){ authInfo, appPk, ... }Present QR Code (with authInfo)POST response (signed by user)auth.verify(response)Verification Result (claims)

new WalletAuthenticator(config)#

Creates an instance of the DID Authenticator. The constructor requires your application's wallet and information, which will be presented to the user in their DID Wallet during the authentication process.

Param

Type

Required

Description

config.wallet

WalletObject | Function

Yes

The application's wallet instance or a function that returns one. It is used to sign requests sent to the user's wallet.

config.appInfo

ApplicationInfo | Function

Yes

Information about your application (name, description, icon) to be displayed in the user's wallet.

[config.delegator]

WalletObject | Function

No

A wallet that delegates authority to config.wallet. Useful in scenarios where an intermediary wallet acts on behalf of a primary application wallet.

[config.delegation]

string | Function

No

The JWT proving the delegation relationship between delegator and wallet.

[config.memberAppInfo]

ApplicationInfo | Function

No

Secondary application information, often used in multi-tenant or platform-based applications.

[config.chainInfo]

ChainInfo | Function

No

The blockchain information required for on-chain operations, such as transaction signing.

[config.timeout]

number

No

Timeout in milliseconds for asynchronous operations when generating claims. Defaults to 8000.

[config.baseUrl]

string

No

The base URL of your application. If not provided, it's often inferred from the request object.

[config.tokenKey]

string

No

The query parameter key for the session token. Defaults to '_t_'.

Example

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

// The application's own wallet
const appWallet = fromRandom().toJSON();

const auth = new WalletAuthenticator({
wallet: appWallet,
baseUrl: 'https://myapplication.com',
appInfo: {
name: 'My App',
description: 'A great application using DID-Auth.',
icon: 'https://myapplication.com/logo.png',
link: 'https://myapplication.com',
},
chainInfo: {
host: 'https://beta.abtnetwork.io/api',
id: 'beta',
},
});


Methods#

.uri(params)#

Generates a deep link URL that can be rendered as a QR code for a DID Wallet to scan and consume.

Param

Type

Description

params.baseUrl

string

The base URL for the callback, typically inferred from the incoming request.

[params.pathname]

string

The path for the callback URL. Defaults to ''.

[params.token]

string

The unique session token for this authentication request.

[params.query]

object

Any additional query parameters to persist in the callback URL.

Returns string

Example

const deepLink = auth.uri({
baseUrl: 'https://myapplication.com',
pathname: '/api/auth/callback',
token: 'z2q5y3x8w7v6',
query: { a: 1 }
});

// Result: https://abtwallet.io/i/?action=requestAuth&url=https%3A%2F%2Fmyapplication.com%2Fapi%2Fauth%2Fcallback%3Fa%3D1%26_t_%3Dz2q5y3x8w7v6
console.log(deepLink);

.sign(params)#

Signs an authentication request to be sent to the wallet. This method packages your application info and the claims you are requesting into a secure JWT.

Param

Type

Description

params.claims

object

The information your application requests from the user. See Understanding Claims.

params.context

object

An object containing request-specific context, such as the token and user details (userDid, userPk) if available.

[params.pathname]

string

The path for the callback URL, which will be embedded in the JWT.

[params.baseUrl]

string

The base URL for the callback.

[params.challenge]

string

A random challenge string to prevent replay attacks.

Returns Promise<object>

Example

const { challenge, token } = session; // Assume you have a session object

const authRequest = await auth.sign({
challenge,
claims: {
profile: {
description: 'Please provide your name and email.',
items: ['fullName', 'email'],
},
},
context: { token },
pathname: '/api/auth/callback',
baseUrl: 'https://myapplication.com',
});

// The authInfo is the JWT to be sent to the wallet
console.log(authRequest.authInfo);

Example Response

{
"appPk": "z8VwAVc5p9yYp1s1q3t5u7w9x2z4r6v8...",
"authInfo": "eyJhbGciOiJFZERTQSIsImtpZCI6ImRpZDphYnQ6...",
"sensitive": false
}

.verify(data)#

Verifies a DID-Auth response sent from the wallet. It decodes the JWT, validates the signature against the user's public key, and returns the claims provided by the user.

Param

Type

Description

data

object

The payload posted back from the wallet, containing userInfo (the JWT) and userPk.

[locale]

string

The locale for error messages ('en' or 'zh'). Defaults to 'en'.

[enforceTimestamp]

boolean

Whether to enforce the JWT's timestamp validity. Defaults to true.

Returns Promise<object>

Example

// 'walletResponse' is the body of the POST request from the wallet
async function handleWalletResponse(walletResponse) {
try {
const { userDid, claims } = await auth.verify(walletResponse);
console.log(`Verified user: ${userDid}`);
console.log('Received claims:', claims);

// claims will be an array like:
// [{ type: 'profile', fullName: 'Alice', email: 'alice@example.com' }]

} catch (error) {
console.error('Auth verification failed:', error.message);
}
}

Example Response

{
"token": "z2q5y3x8w7v6",
"userDid": "zNKpA8BAbL43g9gAN2i2A3g...",
"userPk": "z8VwAVc5p9yYp1s1q3t5u7w9x2z4r6v8...",
"claims": [
{
"type": "profile",
"fullName": "Alice",
"email": "alice@example.com"
}
],
"action": "responseAuth",
"challenge": "...",
"timestamp": 1678886400
}

.signResponse(params)#

Signs a simple, plain response to be displayed in the wallet after an action. This is useful for showing success or error messages, or for chaining multiple authentication workflows.

Param

Type

Description

[params.response]

object

An arbitrary JSON object to be returned to the app.

[params.errorMessage]

string

An error message to display in the wallet. If set, status will be 'error'.

[params.successMessage]

string

A success message to display in the wallet.

[params.nextWorkflow]

string

A URL that tells the wallet to start a new authentication flow immediately.

[params.nextUrl]

string

A URL to open in the wallet's built-in webview.

[params.cookies]

object

Key-value pairs to set as cookies in the webview before opening nextUrl.

[params.storages]

object

Key-value pairs to set in localStorage in the webview before opening nextUrl.

Returns Promise<object>

Example

// Sign a success message and redirect the user
const successResponse = await auth.signResponse({
successMessage: 'Payment complete! You will now be redirected.',
nextUrl: 'https://myapplication.com/orders/123',
}, request.baseUrl, request);

// Send this response back to the wallet
res.json(successResponse);


Dynamic Configuration#

For advanced use cases, you can provide functions to the WalletAuthenticator constructor instead of static objects for wallet, appInfo, and chainInfo. These functions are executed for each request, allowing you to dynamically configure the authenticator based on request parameters or other context.

Example: Dynamic appInfo

This example customizes the application description based on the authentication action being performed.

const auth = new WalletAuthenticator({
wallet: appWallet,
appInfo: (params) => {
// params contains request context
const action = params.context.action;
let description = 'Authenticate to access your account.';
if (action === 'checkout') {
description = 'Please confirm your identity to complete the purchase.';
}
return {
name: 'My Dynamic App',
description,
icon: 'https://myapplication.com/logo.png',
};
},
});


Type Definitions#

ApplicationInfo#

Defines the properties of your application that are displayed in the user's wallet.

Name

Type

Description

name

string

Application name.

description

string

Application description.

icon

string

URL of the application's icon/logo.

link

string

Application home page, allowing the user to return to your app from the wallet.

path

string

Deep link URL for the application.

publisher

string

The DID of the application publisher, prefixed with did:abt:.

ChainInfo#

Defines the properties of the blockchain your application interacts with.

Name

Type

Description

id

string

The ID of the chain (e.g., beta).

host

string

The GraphQL endpoint of the chain's node.

type

string

The type of the chain. Defaults to arcblock.

Now that you understand how to create and verify authentication messages, proceed to the WalletHandlers documentation to learn how to easily integrate the entire authentication lifecycle into an Express.js application.