简体   繁体   中英

Metamask / Web3: Authenticating a user after metamask stopped injecting web3 into the browser

I want to create a passwordless authentication (using Metamask to sign a message; then validate the message on the server and then assign a JWT token). I want the part for signing a message to be written inside a vanila javascript file.

Most of the articles I see online are from 2018 and talk about using web3.eth.personal.sign method from web3 which being injected into the browser by Metamask. However I understand this is no longer the case with Metamask. Now that web3 is not injected anymore, what funcitons do I call to sign a message with Metamask?

What I've attempted... I understand there's a window.ethereum object injected into the browser but I can't seem to find an equivalent function in Metamask Documentaiton for web3.eth.personal.sign

I'm guessing the alternative is to use web3 without window.ethereum but how to I inject this into a vanilla javascript file? Also how do I ensure that the message is signed by Metamask if I just use web3 as standalone?

You could use the web3 npm package . Then you can connect it to Metamask with:

import Web3 from "web3";

window.ethereum.request({ method: "eth_requestAccounts" });
const web3 = new Web3(window.ethereum);

This will make metamask popup and ask the user to select an account.

Then to sign a message you can call web3 with:

const dataToSign = "My test message";
const accounts = await web3.eth.getAccounts();
const signature = await web3.eth.sign(dataToSign, accounts[0]);

Documentation: https://web3js.readthedocs.io/en/v1.3.4/web3-eth.html#sign

This will cause Metamask to ask the user to sign the data with their currently active account. I'm not sure how to validate if the signature is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM