Comprehensive guide for web3 authentication patterns covering essential concepts, practical examples, and production best practices.
Web3 authentication patterns define how users prove their identity across decentralized systems, from wallets to dApps, smart contracts to off-chain services. This is essential when a user must sign transactions, interact with multiple contracts, and maintain consistent identity across chains—without relying on centralized credentials. It matters most when users move between apps that demand cryptographic proof of ownership, such as signing a message to verify a wallet address or submitting a transaction that requires a signature from a hardware wallet.
To authenticate a user in a dApp, the application must verify that the user controls a specific blockchain address. This is most commonly achieved through message signing.
The dApp generates a challenge message, typically in JSON format, and sends it to the user’s wallet. The wallet prompts the user to sign the message using the associated private key. The signature is returned to the dApp, which validates it against the expected message and public key.
A standard message signing flow using ECDSA with secp256k1 (used by Ethereum and Solana) follows this sequence:
{
"domain": {
"name": "My dApp",
"version": "1",
"chainId": 1,
"verifyingContract": "0x742d35Cc6634C0532925a3b8D4C05C3F25533124"
},
"types": {
"EIP712Domain": [
{ "name": "name", "type": "string" },
{ "name": "version", "type": "string" },
{ "name": "chainId", "type": "uint256" },
{ "name": "verifyingContract", "type": "address" }
],
"Login": [
{ "name": "message", "type": "string" },
{ "name": "nonce", "type": "bytes32" }
]
},
"primaryType": "Login",
"message": {
"message": "Login to My dApp",
"nonce": "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b"
}
}
message using the signTypedData_v4 method from EIP-712. The result is a bytes signature in r|s|v format.ecrecover function in Solidity or a library such as ethers or web3.py.After signing, the dApp must verify the signature and optionally create a session token for the user.
In a typical flow, the dApp calls the verifyTypedData function with the domain, types, and message:
function verifyTypedData(
bytes32 domainSeparator,
bytes32 structHash,
bytes memory signature
) external pure returns (address signer) {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
return ecrecover(digest, signature[64], signature[0:32], signature[32:64]);
}
The domainSeparator is computed as:
bytes32 domainSeparator = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
verifyingContract
)
);
The dApp uses the signer address to create a session, often storing it in a database with a session_token and expires_at timestamp.
chainId: The dApp expects chainId = 1, but the wallet signs for chainId = 137. The signature is valid but the user is logged into the wrong network.verifyingContract: The contract address used in the domain does not match the one in the dApp, leading to validation failure even when the signature is correct.nonce reuse: If the same nonce is used across multiple logins, the dApp may accept a stale signature, causing replay attacks.bytes signature but the dApp expects r|s|v as bytes32[3], resulting in ecrecover failing silently.When the authentication logic is fully on-chain, the user must call a specific contract method to prove identity.
authenticate on a Smart ContractThe dApp invokes a authenticate method on a AuthManager contract:
function authenticate(bytes32 challenge, bytes memory signature) external returns (bool success) {
address signer = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", challenge)),
signature[64],
signature[0:32],
signature[32:64]
);
if (signer == msg.sender) {
// Record authentication
auths[signer] = block.timestamp;
emit Authenticated(signer, block.timestamp);
return true;
}
return false;
}
The client-side code to call this function using ethers.js:
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const challenge = ethers.utils.solidityKeccak256(
["string"],
["Authenticate to My dApp"]
);
const signature = await signer.signMessage(ethers.utils.arrayify(challenge));
const contract = new ethers.Contract(
"0x742d35Cc6634C0532925a3b8D4C05C3F25533124",
[
"function authenticate(bytes32 challenge, bytes memory signature) returns (bool)"
],
signer
);
const tx = await contract.authenticate(challenge, signature);
await tx.wait();
console.log("Authentication successful");
challenge not properly hashed: The smart contract expects keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", challenge)), but the client sends keccak256(challenge) directly. The ecrecover fails because the digest is not prefixed with 0x19Ethereum Signed Message:\n32.signature not r|s|v: The client sends a bytes signature with r, s, and v appended, but the contract expects bytes32[3]. The v byte is read as v[0], causing ecrecover to fail.msg.sender mismatch: The user calls authenticate from a wallet that is not the signer, leading to a false return value even though the signature is correct.Once authenticated, users may need to maintain sessions across multiple chains, each with different identity requirements.
After successful authentication, the dApp issues a JWT token containing:
sub: the user’s wallet addressiss: the dApp’s contract addressiat: the time of issuanceexp: the expiration timeaud: the list of chains the session is valid forExample JWT payload:
{
"sub": "0x742d35Cc6634C0532925a3b8D4C05C3F25533124",
"iss": "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b",
"iat": 1700000000,
"exp": 1700003600,
"aud": [
"1",
"137",
"42"
]
}
The dApp validates the JWT using a shared secret or public key from a AuthConfig contract.
A service on chain 137 (Polygon) must verify that a session token issued on Ethereum (chain 1) is valid.
The service queries the AuthConfig contract on Ethereum to retrieve the public key and validates the JWT using jose or jsonwebtoken libraries.
const jwt = require('jsonwebtoken');
const { getPublicKey } = require('./authConfig');
const publicKey = await getPublicKey('0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b');
const decoded = jwt.decode(token, { complete: true });
if (!decoded) throw new Error('Invalid JWT');
const isValid = jwt.verify(token, publicKey, {
audience: ['1', '137', '42'],
issuer: '0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b'
});
if (!isValid) {
throw new Error('JWT validation failed');
}
aud: ["1", "137"], but the service expects aud: ["1"]. The service accepts a session from Polygon but rejects it.iss claim is 0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b, but the AuthConfig contract returns a public key for 0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2c. The signature is valid but the issuer is incorrect.exp is set to 1700003600, but the service’s clock is 15 seconds behind. The session expires before it’s even accepted.Some dApps allow users to customize their authentication flow by specifying parameters such as message content, expiration time, or additional metadata.
The dApp sends a POST /auth/sign request with the following body:
{
"message": "Sign to authenticate on My dApp",
"chainId": 1,
"verifyingContract": "0x742d35Cc6634C0532925a3b8D4C05C3F25533124",
"expiresIn": 3600,
"scope": [
"read:profile",
"write:posts"
],
"nonce": "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b"
}
The wallet signs the message using eth_signTypedData_v4 with the provided domain, types, and message. The signature is returned to the dApp, which validates it and creates a session.
The dApp stores the scope and expiresIn values in the session record and uses them to control access to protected endpoints.
The scope field is a list of permissions, such as:
read:profile: read the user’s profile datawrite:posts: create and edit postsdelete:posts: delete any postA POST /api/posts endpoint checks the user’s session for write:posts and delete:posts scopes.
scope field: The dApp expects scope, but the JWT does not include it. The user is logged in but lacks permissions.expiresIn in seconds, but exp in Unix timestamp: The dApp sets exp = iat + expiresIn, but the session is stored with expiresAt as iat + 3600, leading to a mismatched session lifetime.nonce not used: The dApp generates a nonce but fails to include it in the domain or message, resulting in a signature that is valid but not replay-resistant.When a user logs in and the signature validation fails, the dApp must provide clear feedback.
The dApp returns a standard error response when authentication fails:
{
"error": "AuthenticationFailed",
"message": "Signature validation failed",
"code": 401,
"details": {
"expectedChainId": 1,
"receivedChainId": 137,
"expectedContract": "0x742d35Cc6634C0532925a3b8D4C05C3F25533124",
"receivedContract": "0x8a7b6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a7b6",
"expectedDomainSeparator": "0x...",
"receivedDomainSeparator": "0x..."
}
}
The wallet can display this error to the user and allow retrying the signature with corrected parameters.
ecrecover returns address(0): The signature is valid but the signer is 0x0000000000000000000000000000000000000000. The dApp assumes the user is logged in, but the signature was not from any wallet.domainSeparator mismatch: The dApp computes the domain separator but the wallet uses a different one, leading to a signature that is valid but not accepted.These patterns form the foundation of Web3 authentication: users prove identity through cryptographic signatures, sessions are managed across chains, and validation is precise, failure-tolerant, and extensible.
This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy