How To Build a Web3 Login To Authenticate Users
Login with Web3 has never been easier. With a click of a button, you can log into the dApp with the security of the blockchain. Secure, fast, and efficient.
Web3 and the blockchain are the future. But we’re not there yet. The adoption of these technologies is happening slowly.
Good use case dApps or decentralized apps are what we need. dApps that help users and solve a problem. Not dApps that are made just to ride the hype train.
The first part of any app or dApp is login. Traditional apps use OAuth, which basically means login with Google, Twitter, etc.
Web3 adds another layer of security. You have to use a wallet like Metamask to login. On login, you will be prompted to sign a transaction. Thanks to cryptography, this process is the most secure login out there.
So what is the flow of this process?
It goes like this
- Connect wallet to website
- Get message to sign from server
- The user signs the message and sends the signature to the server
- The server verifies the signature and returns an access token
Creating the express server
Any time the user wants to login, the server must send a nonce to the frontend. This nonce can be a message or a number.
The reason we use a nonce is for better security. Think of it as an OTP. It’s different every time.
So you need to create an API to send this nonce to the frontend. You can send a particular message or use Math.random() to send a random message.
Once the user receives the nonce and signs with their wallet, you must send the signature back to the backend with the help of a different API route.
Here we make use of the function recover. If the recovered address is the same as the user’s public address, the user is logged in.
Here’s a snippet:
const verified Address = await web3.eth.accounts.recover(message, signature)
Where the message is the nonce sent to the user and the signature is the one received from the user.
Connecting the Wallet
Now let’s take a look at the frontend part. When the user presses the login button, you want a wallet like Metamask to pop up. For this, we use window.ethereum. We check if the user has a wallet installed and, if so, get the accounts associated with it.
We sign the message with Metamask and send the signature using the API from above.
If the user is verified, he or she gets logged in.
It’s that simple!
To better understand how this works, you can test it out on dArticle.io.
You are viewing an NFT