EIPs Explained

ERC-4361 · Final(最终) · ERC · 2021-10-11

ERC-4361: Sign-In with Ethereum

Sign-In with Ethereum(SIWE):钱包签署一条标准的纯文本消息即可登录网站,为应用提供了“使用 Google 登录”之外的自托管替代方案。

它解决什么问题?

许多 dapp 已经允许用户通过用钱包签署消息来"登录",然后设置会话 cookie。但每个网站都自己发明了消息文本。钱包无法把登录请求与其他签名区分开,用户看到的提示五花八门,许多实现还漏掉了重放保护、核对究竟是哪个网站请求了签名等基本措施,这使钓鱼变得很容易。

ERC-4361 规范了消息格式以及双方必须执行的检查,使任何钱包都能识别并安全地显示登录请求,任何服务器也都能用同样的方式验证它。

它如何运作

  1. 网站(依赖方)构造一条 SIWE 消息,通常带有服务器生成的 nonce。
  2. 钱包显示该消息,并使用 ERC-191 的 personal_sign 格式(\x19Ethereum Signed Message:\n<len>)对其签名。
  3. 服务器检查消息字段和签名,然后创建一个绑定到地址的会话。

消息是人类可读的文本,语法严格(用 ABNF 定义):

example.com wants you to sign in with your Ethereum account:
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2

I accept the ExampleOrg Terms of Service: https://example.com/tos

URI: https://example.com/login
Version: 1
Chain ID: 1
Nonce: 32891756
Issued At: 2021-09-30T16:25:24Z

必填字段:domain、address(适用时采用 EIP-55 校验和格式)、URI、Version(1)、Chain ID、Nonce(至少 8 个字母数字字符)和 Issued At。可选字段:scheme、statement、Expiration Time、Not Before、Request ID 以及一组 Resources URI。

关键规则:

  • 钱包必须(MUST)检查 scheme/domain 与请求的真实来源一致,并且在签名前至少要显示域名、地址、声明和资源。这是规范中防钓鱼的核心。
  • EOA 用 ERC-191 的 ecrecover 验证;合约钱包应当(SHOULD)在 Chain ID 指定的链上用 ERC-1271 的 isValidSignature 验证。
  • 服务器必须验证 nonce、时间字段和域名,并把会话绑定到地址,而不是绑定到 ENS 名称这类可能变化的东西上。

示例代码

使用 ethers v6 的客户端,手工构造消息:

import { BrowserProvider } from "ethers";

const provider = new BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
const address = await signer.getAddress();
const { chainId } = await provider.getNetwork();
const nonce = await fetch("/api/nonce").then((r) => r.text()); // server-generated

const message = [
  `${window.location.host} wants you to sign in with your Ethereum account:`,
  address,
  "",
  "Sign in to Example.",
  "",
  `URI: ${window.location.origin}`,
  "Version: 1",
  `Chain ID: ${chainId}`,
  `Nonce: ${nonce}`,
  `Issued At: ${new Date().toISOString()}`,
].join("\n");

const signature = await signer.signMessage(message); // ERC-191 personal_sign
await fetch("/api/verify", { method: "POST", body: JSON.stringify({ message, signature }) });

在服务器端,解析消息,检查域名/nonce/过期时间,然后把 ethers.verifyMessage(message, signature) 的结果与地址比较(对于合约钱包则调用 ERC-1271)。

需要注意

  • 状态:Final。已有实现了解析和验证的库(例如 npm 的 siwe 包);请优先使用它们,而不是手写解析器。
  • 只负责身份认证:授权以及对 Resources 的解释不在范围之内。ERC-5573(ReCaps)在此基础上构建了能力委托。
  • 每次登录都使用新的、高熵的 nonce,并拒绝重复使用的 nonce,否则被截获的签名可能被重放。
  • ERC-1271 的结果取决于链状态,因此当签名者变更时,合约钱包的会话可能需要失效。
  • 选择 ERC-191 而不是 EIP-712,是因为钱包显示纯文本更易读;该消息的设计并不面向链上验证。

#authentication #wallet #siwe #signature #identity

详细信息

作者
Wayne Chang (@wyc), Gregory Rocco (@obstropolos), Brantly Millegan (@brantlymillegan), Nick Johnson (@Arachnid), Oliver Terbu (@awoie)
状态
Final(最终)
类型
Standards Track / ERC
创建日期
2021-10-11
依赖的提案
被以下提案依赖

机器可读数据: Markdown · JSON