DID Connect
DID Connect is an essential part of the Blocklet SDK, enabling secure and seamless authentication for users connecting with DID Wallet. This section details how to integrate DID Connect authentication flows, manage user sessions, and leverage advanced features like federated login and auto-connection within your Blocklet applications. For more general authentication and user management functionalities, refer to the Auth Service documentation.
Core Components#
The DID Connect integration in Blocklet SDK primarily relies on two types of components: Authenticators and Handlers.
Authenticators#
Authenticators are responsible for defining how your Blocklet interacts with the DID Connect protocol, including managing application information, delegators, and delegations. The Blocklet SDK provides two main authenticator classes:
BlockletAuthenticator#
BlockletAuthenticator
is built on @did-connect/authenticator
and is specifically tailored for Blocklet environments. It automatically integrates with the Blocklet Server to fetch relevant application and node information.
Constructor Parameters
Name | Type | Description |
---|---|---|
|
| An object to configure the authenticator. |
|
| (Internal) Automatically set by |
|
| (Optional) A function that returns application information. It will be merged with Blocklet's default app info. |
|
| (Optional) A function that returns blockchain network information. |
|
| (Optional) A function that returns the delegator wallet object for federated login. |
|
| (Optional) A function that returns the delegation JWT for federated login. |
Example
import BlockletAuthenticator from '@blocklet/sdk/lib/connect/authenticator';
const authenticator = new BlockletAuthenticator({
// Custom options can be passed here
// For example, to override default appInfo or add custom chainInfo
});
This example shows a basic initialization of BlockletAuthenticator
. The SDK automatically handles most of the necessary configurations based on the Blocklet's environment variables.
WalletAuthenticator#
WalletAuthenticator
is based on @arcblock/did-auth
and provides a more general-purpose authenticator. It also automatically integrates with the Blocklet's wallet and environment.
Constructor Parameters
WalletAuthenticator
accepts similar options to BlockletAuthenticator
.
Name | Type | Description |
---|---|---|
|
| An object to configure the authenticator. |
|
| (Internal) Automatically set by |
|
| (Optional) Custom application information function. |
|
| (Optional) Custom chain information function. |
|
| (Optional) Custom delegator function for federated login. |
|
| (Optional) Custom delegation function for federated login. |
Example
import WalletAuthenticator from '@blocklet/sdk/lib/wallet-authenticator';
const authenticator = new WalletAuthenticator({
// Custom options if needed
});
Common Authenticator Properties#
Both BlockletAuthenticator
and WalletAuthenticator
leverage a shared utility function, getAuthenticatorProps
, to resolve key properties like appInfo
, chainInfo
, delegator
, and delegation
. These properties are crucial for defining how your Blocklet presents itself to DID Wallet and handles advanced features like federated login.
1. appInfo
This function provides the application's metadata (name, description, icon, link) to the DID Wallet during the connection process. It dynamically determines the correct application information based on whether the Blocklet is operating as a standalone application or participating in a federated login scenario.
Parameters
Name | Type | Description |
---|---|---|
|
| The Express.js request object, used to extract headers like |
|
| The base URL of the Blocklet, used for constructing icon and link URLs. |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing the application's public information. |
Example appInfo
Structure
{
"name": "My Blocklet App",
"description": "Connect to My Blocklet App",
"icon": "/blocklet/logo?v=1.0.0",
"link": "https://my-blocklet.abtnode.com",
"updateSubEndpoint": true,
"subscriptionEndpoint": "/_/blocklet/websocket",
"nodeDid": "did:abt:zxxx..."
}
When sourceAppPid
is present (indicating a federated login), this function fetches information about the federated master Blocklet, ensuring the DID Wallet connects to the correct parent application.
2. memberAppInfo
This function is specifically designed to provide application information for member applications within a federated Blocklet setup. It ensures that when a user connects to a member Blocklet, the DID Wallet receives the correct context about that specific member application, while still being aware of the overall federated structure. If the sourceAppPid
is not present or the Blocklet is not federated, it returns null
.
Parameters
Name | Type | Description |
---|---|---|
|
| The Express.js request object. |
|
| The base URL of the Blocklet. |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing the member application's public information, or |
Example memberAppInfo
Structure (if applicable)
{
"name": "My Member App",
"description": "Connect to My Member App",
"icon": "/blocklet/logo?v=1.0.0",
"link": "https://my-member-blocklet.abtnode.com",
"updateSubEndpoint": true,
"subscriptionEndpoint": "/_/blocklet/websocket",
"nodeDid": "did:abt:zxxx...",
"publisher": "did:abt:blocklet_app_pid"
}
Handlers#
Handlers manage the lifecycle of DID Connect sessions, including session creation, updates, and interactions with DID Wallet for features like auto-connection and notifications. The Blocklet SDK provides specialized handlers to streamline these processes.
createConnectHandlers
#
This function creates a set of DID Connect session handlers, extending the base handlers from @did-connect/handler
. It customizes the handleSessionCreate
method to enable auto-connection with DID Wallet by sending notifications.
Parameters
Name | Type | Description |
---|---|---|
|
| An instance of |
|
| An object for session storage. |
|
| (Optional) A logger instance (defaults to |
|
| (Optional) The WebSocket path for the DID Connect service. |
|
| (Optional) A custom function to send notifications (defaults to |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing the DID Connect session handlers. |
Key Method: handleSessionCreate
This method is overridden to send an auto-connect notification to the DID Wallet if a connectedDid
is found in the session. This enables a smoother user experience where the wallet can automatically connect without requiring the user to scan a QR code.
Parameters for handleSessionCreate
Name | Type | Description |
---|---|---|
|
| The context object for the session creation, containing request details. |
Example
import createConnectHandlers from '@blocklet/sdk/lib/connect/handler';
import BlockletAuthenticator from '@blocklet/sdk/lib/connect/authenticator';
import MemoryStorage from '@blocklet/sdk/lib/storage/memory'; // Example storage
const authenticator = new BlockletAuthenticator();
const storage = new MemoryStorage();
const connectHandlers = createConnectHandlers({
authenticator,
storage,
// Optional: customize logger or sendNotificationFn
});
// Use connectHandlers with your Express.js app or similar framework
// For example, in an API route:
// app.post('/api/did/connect', connectHandlers.handleSessionCreate);
WalletHandlers#
WalletHandlers
extends @arcblock/did-auth
's WalletHandlers
and is designed for broader DID Connect use cases, especially when integrating with the DID Wallet. It provides enhanced control over auto-connection and integrates with the Blocklet SDK's notification service.
Constructor Parameters
Name | Type | Description |
---|---|---|
|
| (Optional) Enables auto-connect to DID Wallet (wallet does not need to scan QR code). Defaults to |
|
| (Optional) If |
|
| (Optional) Custom function to send notifications to users (defaults to |
|
| (Optional) Custom function to send messages to the relay service (defaults to |
|
| (Optional) Additional options passed to the base |
Key Method: attach
This method is overridden to enable auto-connection logic. It checks for a connected DID and, if found, sends a connect
notification to the DID Wallet. This notification contains the deep link and a check URL, prompting the wallet to auto-connect to the session.
Parameters for attach
Name | Type | Description |
---|---|---|
|
| (Optional) A callback function executed at the start of the authentication process. It can return extra parameters for the session. |
|
| Additional options passed to the base |
Example
import WalletHandlers from '@blocklet/sdk/lib/wallet-handler';
import WalletAuthenticator from '@blocklet/sdk/lib/wallet-authenticator';
import MemoryStorage from '@blocklet/sdk/lib/storage/memory'; // Example storage
const authenticator = new WalletAuthenticator();
const storage = new MemoryStorage();
const handlers = new WalletHandlers({
autoConnect: true, // Enable auto-connect
connectedDidOnly: false,
// Custom notification functions can be passed here if needed
});
// Attach handlers to an authentication endpoint
// This is typically used with an Express.js router
// router.get('/auth/connect', handlers.attach({ authenticator, storage }));
// Example usage within a route handler (simplified):
async function handleConnectRequest(req, res) {
try {
const authUrl = await handlers.attach({
authenticator,
storage,
onStart: async (params) => {
console.log('Authentication session started:', params);
// Return any extra data to be included in the session
return { customData: 'some_value' };
},
onComplete: (context) => {
console.log('Authentication complete:', context.session.userDid);
res.json({ message: 'Login successful', userDid: context.session.userDid });
},
onError: (error) => {
console.error('Authentication error:', error);
res.status(500).json({ error: error.message });
},
})(req, res);
// For QR code display, you'd render this authUrl or deepLink
if (authUrl) {
res.json({ authUrl, deepLink: authUrl.replace('/auth', '/i/') });
}
} catch (error) {
console.error('Error initiating connect:', error);
res.status(500).json({ error: error.message });
}
}
DID Connect Flow Overview#
This sequence diagram illustrates the typical DID Connect authentication flow within a Blocklet, highlighting the roles of the Authenticator and Handlers in facilitating user connection and auto-connection with DID Wallet.
This diagram provides a visual representation of how the components interact during a DID Connect authentication. The Authenticator
sets up the foundational information, while the Handler
manages the session flow, including the critical auto-connection feature facilitated by the Notification Service
.
This section covered the integration of DID Connect within your Blocklet applications, detailing the roles of Authenticators
and Handlers
in managing secure user connections and enabling features like auto-connection and federated login. You now have a comprehensive understanding of how to leverage these core components. For information on sending and receiving various types of notifications, proceed to the Notifications section.