Ethers.js – Signing a Message to Validate EOA Identity

dapp-developmentethers.jsjavascriptwalletsweb3js

When you use dApps that have read/write functions that require auth, sometimes the dApp will have you sign a message to prove you are the EOA you claim to be. OpenSea does this when you want to modify your settings, for instance.

I am not entirely sure how to properly phrase this, but what I am looking for is an example of how I can capture a signature from an EOA that I can then validate with Ethers.js on a backend to authenticate a user.

The idea is upon wallet connect, I want to be able to send a message to the backend login server, validate the message with ethers, then sign a JWT cookie as a response to the frontend.

How does one use Ethers.js to sign such a message and then later validate it?

Best Answer

const message = 'Hello';

// In frontend
const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send('eth_requestAccounts', []) // connects MetaMask
const signer = provider.getSigner()
const signature = await signer.signMessage(message);

// On server
const recoveredAddress = ethers.utils.verifyMessage(message, signature);

assert(recoveredAddress === await signer.getAddress());
Related Topic