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.
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 |
|---|---|---|---|
|
| Yes | The application's wallet instance or a function that returns one. It is used to sign requests sent to the user's wallet. |
|
| Yes | Information about your application (name, description, icon) to be displayed in the user's wallet. |
|
| No | A wallet that delegates authority to |
|
| No | The JWT proving the delegation relationship between |
|
| No | Secondary application information, often used in multi-tenant or platform-based applications. |
|
| No | The blockchain information required for on-chain operations, such as transaction signing. |
|
| No | Timeout in milliseconds for asynchronous operations when generating claims. Defaults to |
|
| No | The base URL of your application. If not provided, it's often inferred from the request object. |
|
| No | The query parameter key for the session token. Defaults to |
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 |
|---|---|---|
|
| The base URL for the callback, typically inferred from the incoming request. |
|
| The path for the callback URL. Defaults to |
|
| The unique session token for this authentication request. |
|
| 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 |
|---|---|---|
|
| The information your application requests from the user. See Understanding Claims. |
|
| An object containing request-specific context, such as the |
|
| The path for the callback URL, which will be embedded in the JWT. |
|
| The base URL for the callback. |
|
| 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 |
|---|---|---|
|
| The payload posted back from the wallet, containing |
|
| The locale for error messages ( |
|
| Whether to enforce the JWT's timestamp validity. Defaults to |
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 |
|---|---|---|
|
| An arbitrary JSON object to be returned to the app. |
|
| An error message to display in the wallet. If set, status will be |
|
| A success message to display in the wallet. |
|
| A URL that tells the wallet to start a new authentication flow immediately. |
|
| A URL to open in the wallet's built-in webview. |
|
| Key-value pairs to set as cookies in the webview before opening |
|
| Key-value pairs to set in localStorage in the webview before opening |
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 |
|---|---|---|
|
| Application name. |
|
| Application description. |
|
| URL of the application's icon/logo. |
|
| Application home page, allowing the user to return to your app from the wallet. |
|
| Deep link URL for the application. |
|
| The DID of the application publisher, prefixed with |
ChainInfo#
Defines the properties of the blockchain your application interacts with.
Name | Type | Description |
|---|---|---|
|
| The ID of the chain (e.g., |
|
| The GraphQL endpoint of the chain's node. |
|
| The type of the chain. Defaults to |
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.