跳转到内容

登录认证会话

使用 D9 钱包完成用户登录认证,并由后端校验凭证后签发会话。

前置条件: 需自行提供两个后端接口(本示例不包含服务端路由实现):

  • POST /api/auth/challenges — 生成登录 Challenge(第 1 步),持久化存储后返回给前端。
  • POST /api/auth/challenges/:requestId/consume — 对照已存储的 Challenge 校验 CACAO 认证凭证,以原子操作标记 Nonce 已使用并签发安全会话。校验步骤详见登录认证 (SIWX)。

缺少服务端验签时不会建立任何有效登录状态——仅有 Challenge 并不能证明用户身份。

1. 在服务端生成 Challenge(server/challenge.ts)

Section titled “1. 在服务端生成 Challenge(server/challenge.ts)”
import crypto from "node:crypto";
import type { D9AuthenticateParams } from "@d9-network/dapp-connector/protocol";
export function createChallengePayload(
appDomain: string,
appUri: string,
requestId: string,
): D9AuthenticateParams {
const now = new Date();
const expiresAt = new Date(now.getTime() + 5 * 60 * 1000); // 有效期 5 分钟
return {
domain: appDomain,
uri: appUri,
chains: ["d9net:000000000000000000000000000000d9"],
nonce: crypto.randomBytes(16).toString("hex"),
requestId,
version: "1",
type: "caip122",
iat: now.toISOString().replace(/\.\d{3}Z$/, "Z"),
exp: expiresAt.toISOString().replace(/\.\d{3}Z$/, "Z"),
statement: "Sign in to My DApp.",
};
}

在 POST /api/auth/challenges 返回该对象之前,务必先将其写入服务端存储。

2. 在浏览器端发起登录(src/authenticate.ts)

Section titled “2. 在浏览器端发起登录(src/authenticate.ts)”
import { Effect, Schema } from "effect";
import { D9DAppConnector } from "@d9-network/dapp-connector";
import { D9AuthenticateParamsSchema } from "@d9-network/dapp-connector/protocol";
import { walletRuntime } from "./wallet";
export async function signIn(
showPairing: (uri: string, cancel: () => Promise<void>) => void,
hidePairing: () => void,
) {
// 1. 向后端申请新的 Challenge
const issued = await fetch("/api/auth/challenges", {
method: "POST",
headers: { "Content-Type": "application/json" },
});
if (!issued.ok) throw new Error("Challenge 请求失败");
const rawChallenge = await issued.json();
return walletRuntime.runPromise(
Effect.scoped(Effect.gen(function* () {
const connector = yield* D9DAppConnector;
const params = yield* Schema.decodeUnknownEffect(D9AuthenticateParamsSchema)(rawChallenge);
// 2. 请求 D9 钱包签署 SIWX 认证消息
const start = yield* connector.authenticate(params);
showPairing(start.uri, () => walletRuntime.runPromise(start.cancel));
yield* Effect.forkScoped(
start.walletConnected.pipe(Effect.andThen(Effect.sync(hidePairing))),
);
const result = yield* start.response;
const [auth] = result.auths;
if (result.auths.length !== 1 || !auth) {
throw new Error("预期仅返回一条已批准的认证凭证");
}
// 3. 将 CACAO 凭证提交至后端校验
const consumed = yield* Effect.tryPromise(() =>
fetch(`/api/auth/challenges/${encodeURIComponent(params.requestId)}/consume`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ cacao: auth }),
}),
);
if (!consumed.ok) throw new Error("登录验签失败");
return yield* Effect.tryPromise(() => consumed.json());
})).pipe(Effect.ensuring(Effect.sync(hidePairing))),
);
}

由界面层传入 showPairing(负责展示二维码与取消按钮)及 hidePairing 回调。

signIn 返回后端响应,且用户获得已认证的服务端会话。

报错信息 处理方式
Challenge 请求失败 检查 POST /api/auth/challenges 接口是否正常返回。
预期仅返回一条已批准的认证凭证 用户须在钱包弹窗中仅批准一个账户登录。
登录验签失败 后端拒绝了认证凭证,请对照登录认证 (SIWX)检查校验逻辑,或确认 Challenge 未过期且未被重复使用。