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

Set up with Express.js


Integrating decentralized identity into your web application is straightforward with did-auth and the Express.js framework. The WalletHandlers class is designed to plug directly into your Express app, automatically creating all the necessary API endpoints for a complete authentication flow. This guide walks you through setting up a simple user login.

1. Installation#

First, add the necessary packages to your project.

npm install express @arcblock/did-auth @arcblock/did-auth-storage-memory @ocap/wallet
  • express: The web server framework.
  • @arcblock/did-auth: The core library containing WalletHandlers and WalletAuthenticator.
  • @arcblock/did-auth-storage-memory: A simple, in-memory storage adapter for session tokens. For production, you may want to use a persistent adapter.
  • @ocap/wallet: A library to generate and manage DID wallets. You'll need one for your application itself.

2. Initialize the Server and DID Auth#

Create a server.js file. In this file, you will set up your Express server and initialize the DID Auth components.

Your application needs its own identity (a DID wallet) to sign requests and prove its identity to the user's wallet.

// server.js
const express = require('express');
const { WalletHandlers, WalletAuthenticator } = require('@arcblock/did-auth');
const MemoryAuthStorage = require('@arcblock/did-auth-storage-memory');
const { fromRandom } = require('@ocap/wallet');

// 1. Create a wallet for your application
const appWallet = fromRandom();
console.log(`Application DID created: ${appWallet.address}`)

// 2. Initialize core components
const tokenStorage = new MemoryAuthStorage();

const authenticator = new WalletAuthenticator({
wallet: appWallet.toJSON(),
appInfo: ({ baseUrl }) => ({
name: 'My Express App',
description: 'A demo app for DID Auth',
icon: 'https://arcblock.oss-cn-beijing.aliyuncs.com/images/wallet-round.png',
link: baseUrl,
}),
});

const handlers = new WalletHandlers({
tokenStorage,
authenticator,
});

// 3. Create and configure the Express app
const app = express();
const port = 3000;

// The root endpoint can serve a simple page with the login button
app.get('/', (req, res) => {
res.send('<h1>DID Auth Express Demo</h1><a href="/login">Login with DID Wallet</a>');
});

3. Attach Authentication Routes#

Use the handlers.attach() method to add the DID Auth API endpoints to your Express app. You define the action, specify what claims to request, and provide callbacks to handle the results.

// server.js (continued)

handlers.attach({
app,
action: 'login', // This will create routes under /api/did/login
claims: {
profile: () => ({
fields: ['fullName', 'email'],
description: 'Please provide your name and email to log in.',
}),
},
onAuth: async ({ claims, userDid, userPk }) => {
console.log('User successfully authenticated!');
console.log('User DID:', userDid);
console.log('User Public Key:', userPk);
const profile = claims.find((x) => x.type === 'profile');
if (profile) {
console.log('User Profile:', profile);
}
// Here, you would typically create a session, set a cookie, etc.
return { successMessage: 'Login successful!' };
},
onStart: (data, res) => {
// When the flow starts, redirect the user to a page that will render the QR code
// For this simple example, we are not building a dedicated login page
// and will just return the auth URL directly.
return res.json(data);
}
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
console.log(`Application wallet address: ${appWallet.address}`);
});

In this setup, when onAuth is triggered, it logs the user's DID and the profile information they shared from their wallet. The onStart callback is customized to return the session data as JSON, which a frontend would use to display the login QR code.

4. The Authentication Flow#

Once your server is running, WalletHandlers manages the entire authentication process.

DID WalletExpress ServerBrowserDID WalletExpress ServerBrowserhandlers.attach() creates this endpointWallet requests the challengeWallet submits signed claimsonAuth() callback is executedFrontend polls for statusGET /api/did/login/tokenJSON { url: 'did-auth://...' }User scans QR code with the auth URLGET /api/did/login/authJWT(signed challenge & claims)POST /api/did/login/authJWT(signed success response)GET /api/did/login/statusJSON { status: 'succeed', ... }

Generated API Endpoints#

Attaching handlers for a given action (e.g., login) automatically creates a standard set of RESTful endpoints under the prefix /api/did/{action}.

Endpoint

Method

Description

/api/did/{action}/token

GET, POST

Creates a new session and returns the authentication URL for the QR code.

/api/did/{action}/status

GET

Allows the frontend to poll for the session status (e.g., created, scanned, succeed, error).

/api/did/{action}/auth

GET

Called by DID Wallet to fetch the authentication challenge and requested claims.

/api/did/{action}/auth

POST

Called by DID Wallet to submit the user's signed response. Triggers the onAuth callback.

/api/did/{action}/auth/submit

GET

A compatibility endpoint for older wallets that submit responses via GET/JSONP.

/api/did/{action}/timeout

GET

An endpoint to manually expire a session token.

Next Steps#

With this basic setup, you have a fully functional DID authentication system. Now you can explore more advanced scenarios: