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

Getting Started


This guide provides a minimal, step-by-step example to help you set up and run a basic DID Connect session in a Node.js application. By the end, you will have a working server that can request a user's profile information via a DID Wallet.

Prerequisites#

Before you begin, ensure you have Node.js and a package manager like npm or pnpm installed on your system.

Step 1: Install Dependencies#

First, install the core @arcblock/did-connect-js library, along with express to run a web server and a simple storage adapter to manage session tokens. We'll use @arcblock/did-connect-storage-nedb for this example.

npm install express @arcblock/did-connect-js @arcblock/did-connect-storage-nedb @ocap/wallet
// or
pnpm install express @arcblock/did-connect-js @arcblock/did-connect-storage-nedb @ocap/wallet

Step 2: Configure the Authenticator and Handlers#

The DID Connect process is managed by two main components:

  • WalletAuthenticator: Represents your application's identity. It holds the application's DID, metadata (like name and icon), and the blockchain information it connects to. It is responsible for signing requests sent to the user's wallet.
  • WalletHandlers: Manages the HTTP endpoints and lifecycle callbacks for a DID Connect session. It integrates with frameworks like Express to handle communication with the wallet.

Create a file named server.js and add the following setup code:

const SimpleStorage = require('@arcblock/did-connect-storage-nedb');
const { fromRandom } = require('@ocap/wallet');
const { WalletAuthenticator, WalletHandlers } = require('@arcblock/did-connect-js');

// 1. Create a wallet for your application. In a real app, you would load this from a secure location.
const wallet = fromRandom();

// 2. Initialize the WalletAuthenticator with your application's information.
const authenticator = new WalletAuthenticator({
wallet,
baseUrl: 'http://localhost:3000', // The base URL of your application
appInfo: {
name: 'My First DID Connect App',
description: 'A simple app to demonstrate DID Connect.',
icon: 'https://arcblock.oss-cn-beijing.aliyuncs.com/images/wallet-round.png', // URL to your app's icon
},
chainInfo: {
host: 'https://beta.abtnetwork.io/api', // The GraphQL endpoint of the blockchain
id: 'beta', // The ID of the blockchain
},
});

// 3. Initialize WalletHandlers to manage sessions and callbacks.
const handlers = new WalletHandlers({
authenticator,
tokenStorage: new SimpleStorage({ dbPath: './auth.db' }), // A simple file-based storage for session tokens
});

In this setup:

  • We create a new, random wallet for the application on startup. For a production application, you should generate this once and store it securely.
  • baseUrl is the public-facing URL of your server. The wallet will send responses back to this address.
  • appInfo tells the user's wallet which application is requesting the connection.
  • chainInfo specifies which blockchain the application is interacting with.

Step 3: Attach Handlers to an Express Server#

Now, create an Express application and use the handlers.attach method to create the necessary HTTP endpoints for DID Connect.

const express = require('express');
const app = express();
const port = 3000;

// This middleware is required if your app is behind a proxy
app.set('trust proxy', true);

// 4. Attach the DID Connect session handler to your Express app.
handlers.attach({
app,
action: 'profile', // Unique identifier for this authentication action
claims: {
// Request the user's profile
profile: () => ({
fields: ['fullName', 'email'],
description: 'Please provide your name and email to continue.',
}),
},
// 5. Define a callback to handle the successful authentication.
onAuth: async ({ userDid, claims }) => {
// userDid is the DID of the connected user.
// claims is an array containing the information provided by the user.
try {
const profile = claims.find((x) => x.type === 'profile');
console.log('Login successful!', { userDid, profile });
} catch (err) {
console.error('Error processing authentication:', err);
}
},
});

app.listen(port, () => {
console.log(`Server listening on port ${port}`);
console.log(`To start a session, open a browser and navigate to: http://localhost:3000/api/did/profile/token`);
});

Here's what handlers.attach does:

  • It creates a set of endpoints under /api/did/profile, where profile is the action name.
  • The claims object specifies what information to request from the user. Here, we ask for a profile with the fullName and email fields.
  • The onAuth function is the most important callback. It executes after the user approves the request in their wallet and submits the information. This is where you would typically create a user session, save the profile to a database, or perform other business logic.

Step 4: Run the Application#

Your backend is now ready. Save the server.js file and run it from your terminal:

node server.js

Your server is now running and can handle DID Connect requests. To initiate a login session, you would typically display a QR code on your frontend that points to the URL provided in the console (http://localhost:3000/api/did/profile/token). Scanning this with a DID Wallet will start the connection process.

Next Steps#

You have successfully set up the backend for a DID Connect session. The next step is to integrate the frontend using a library like DID Connect UX to display the QR code and manage the user experience.

To learn more about the complete process and advanced features, explore these sections: