𝗠𝗲𝘁å𝗺å𝘀𝗸 Login - Swap crypto and exchange. Manage your digital assets using 𝗠𝗲𝘁å𝗺å𝘀𝗸 Wallet key vault, encrypted Login, and digital wallet.
Logging into a website via third parties is ubiquitous online. Almost every other member-based website allows you to log in with accounts like Facebook, Twitter, and Google.
If you’ve ever visited NFT marketplaces like OpenSea or Rarible, you would have noticed they allow you to sign in with a crypto wallet like MetaMask.
This login process affirms you’re the owner of the Ethereum address in question and allows the system to authenticate your access. Very similar to how a username and password would allow you access to a gated part of a website.


Before starting this tutorial, I’ll assume you have a basic understanding of Laravel, and that you can initialise a new project in your environment. Even though this tutorial is Laravel-focused, with some tweaking you can apply this to any other PHP project. The concepts remain the same.
I’ve tried to keep this as generic as possible. I only focus on the MetaMask signing and validation, without restricting you to using it with specific front-end technologies (like React or Vue) or authentication scaffolding (like Breeze or Jetstream). This gives you the freedom to implement it with minimal effort into an existing project.
We’ll need the following before we start:
  • A new or existing Laravel project.
  • ​MetaMask installed in your browser.


We’ll start out with some boilerplate code by importing Bootstrap 5 and creating a simple “Log in with MetaMask” button.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MetaMask Login</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"></script>
<div class="container">
<div class="row">
<div class="col-12 text-center">
<button class="btn btn-primary mt-5">Log in with MetaMask</button>
Easy enough. 😀
We’re also importing the ethers.js library that will allow us to interact with the Ethereum blockchain via MetaMask, which in this case acts as the interface to the provider (Infura by default).

Quick tip:

Providers allow us to interact with the Ethereum blockchain. To connect to the network, you need access to a node. Depending on the type of node, it could require a large amount of disk space and bandwidth. Running a node can also be a complex process, especially if you want to focus on development rather than maintaining and operating a node.
Enter, the provider! Companies like Infura provide these nodes as a service, so you don’t need to worry about running your own. Instead, you can access this functionality via their APIs.
You may run into older tutorials that state MetaMask injects web3.js (a library providing similar functionality to ethers.js) into the page by default. This is no longer the case.

Detect the Provider

We’ll start off our new web3Login() function by checking that the browser has a provider available. This would be the case if you have MetaMask installed. You can also test this code where MetaMask is not installed (for example, an incognito window) to confirm the detection works.
Add the click event to the button:
<button class="btn btn-primary mt-5" onclick="web3Login();">Log in with MetaMask</button>
And start off the function with our detection snippet in our <head> below the ethers.js import:
async function web3Login() {
if (!window.ethereum) {
alert('MetaMask not detected. Please install MetaMask first.');
Go ahead and test this in a browser with no MetaMask installed.

Install Laravel Dependencies

Before we continue with the front-end login process, we need to put some endpoints in place. Our login script will need these so the user can sign a message with their wallet, and our system can then verify their signature.
We need to install two dependencies via Composer to help us perform hashing and use elliptic curve cryptography:
composer require kornrunner/keccak
composer require simplito/elliptic-php

Add Laravel Routes

Open your routes/web.php file and add the following routes:
Route::get('/web3-login-message', '[email protected]');
Route::post('/web3-login-verify', '[email protected]');
The first route will return the message that needs to be signed, and the second route will verify the signed message.

Create the Login Controller

Now it’s time to create the controller that will generate the message and perform the verification.
Create a new file called Web3LoginController.php in app/Http/Controllers and add the following code to it:
namespace App\Http\Controllers;
use Elliptic\EC;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use kornrunner\Keccak;
class Web3LoginController
public function message(): string
$nonce = Str::random();
$message = "Sign this message to confirm you own this wallet address. This action will not cost any gas fees.\n\nNonce: " . $nonce;
session()->put('sign_message', $message);
return $message;
public function verify(Request $request): string
$result = $this->verifySignature(session()->pull('sign_message'), $request->input('signature'), $request->input('address'));
// If $result is true, perform additional logic like logging the user in, or by creating an account if one doesn't exist based on the Ethereum address
return ($result ? 'OK' : 'ERROR');
protected function verifySignature(string $message, string $signature, string $address): bool
$hash = Keccak::hash(sprintf("\x19Ethereum Signed Message:\n%s%s", strlen($message), $message), 256);
$sign = [
'r' => substr($signature, 2, 64),
's' => substr($signature, 66, 64),
$recid = ord(hex2bin(substr($signature, 130, 2))) - 27;
if ($recid != ($recid & 1)) {
return false;
$pubkey = (new EC('secp256k1'))->recoverPubKey($hash, $sign, $recid);
$derived_address = '0x' . substr(Keccak::hash(substr(hex2bin($pubkey->encode('hex')), 1), 256), 24);
return (Str::lower($address) === $derived_address);
There’s a lot going on in there, so let’s break it down:

Create the message

The message() method creates the message we’ll supply to the front end. It also includes a random token to ensure the message to sign will be different each time.
This token is usually referred to as a nonce, or number used once. In this case, however, it’s a simple random string.
The purpose of this is to prevent replay attacks where, if a malicious user obtained your signature, they could use that to authenticate as you on the website.
The message is then saved to the session and returned to the front end.

Verify the message

Once you have signed the message with your private key via MetaMask, your Ethereum address as well as the signature is sent to the back end for verification.
If it passes the verification, we determine the Ethereum address that signed the message and ensure it matches the Ethereum address sent from the front end during the signing process.
If that passes, we send an OK or ERROR back to the front end.
It’s also at this point where you can add additional logic like logging the member in or creating a new member record if one doesn’t exist for the Ethereum address in question.

Finalise the Front End

Now that the backend is ready, we can complete the rest of the front end. This will involve launching MetaMask, asking the user to sign the message, and then verifying the signature by using our back-end route.
Below is the full web3Login() function:
async function web3Login() {
if (!window.ethereum) {
alert('MetaMask not detected. Please install MetaMask first.');
const provider = new ethers.providers.Web3Provider(window.ethereum);
let response = await fetch('/web3-login-message');
const message = await response.text();
await provider.send("eth_requestAccounts", []);
const address = await provider.getSigner().getAddress();
const signature = await provider.getSigner().signMessage(message);
response = await fetch('/web3-login-verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
body: JSON.stringify({
'address': address,
'signature': signature,
'_token': '{{ csrf_token() }}'
const data = await response.text();
Let’s break it down:
  • We first set the provider to the MetaMask provided window.ethereum.
  • Next, we grab the message returned from our back end (refresh the page a few times to try this out, you will notice the random token changes every time).
  • Once we have the message, we obtain the user’s Ethereum address and ask them to sign the message.
  • We then POST the address and signature to the back end (along with our Laravel CRSF token) for verification.
  • The result is either an OK or ERROR string which we output in the console.
  • At this point you may elect to show an error message (if applicable) or redirect the user if they were registered or logged in during the back-end verification.


In this tutorial we covered the basics of adding a MetaMask login to your website. I hope this has proven useful!
Original article source at https://www.freecodecamp.org
MetaMask is a cryptocurrency wallet that is available as a browser extension to help you store tokens, interact with decentralized applications, and trade Ethereum.
By connecting users with MyEtherWallet, MetaMask eliminates the need to enter private keys at the execution of each transaction while creating, storing, or trading tokens.
Users can store and manage their Bitcoin, Ether, and other cryptocurrencies using a blockchain wallet, which is available as a digital or online wallet. A blockchain wallet enables cryptocurrency transfers, prevents theft of crypto assets, and allows users to convert them back into their local currencies if needed.
MetaMask is the most popular blockchain wallet today, with monthly active users surpassing 30 million, thus making MetaMask the most widely-used non-custodial crypto wallet in the world. The MetaMask browser extension provides a vital utility for crypto gamers, developers, and newcomers to the blockchain space.
Its community is strong, with over a million downloads, and it has many resources contributing to the project.
The MetaMask browser extension is a browser extension that can act as your Ethereum wallet. Unlike traditional wallets, MetaMask requires no additional plug-ins, so you’re free to use it in any browser.
Once installed, you can view your Ethereum address and send or receive coins to any Ethereum address in turn. MetaMask allows you to stake coins on gambling sites and trade on DEXs, as well as participate in projects like PoolTogether and Compound.
The MetaMask application is available for both desktop and mobile platforms. The downloading process is largely the same on all supported browsers. Before you decide to use this tool, make sure you understand the advantages and disadvantages of the tool.
This comprehensive guide will show you how to install the extension, create a wallet, write down your seed phrase, and send ETH to your wallet.
MetaMask is a private crypto wallet used for storing and swapping cryptocurrencies and NFTs. It comes in two versions which are browser extension and mobile application. Its fundamental purpose is to access Ethereum-enabled applications. It also helps the user in creating and managing identities of their own so that a secure interface is provided to the user to review the transaction whenever Dapp is performing a transaction and writing to the blockchain. It also helps you by warning you whenever you are about to access a site that is related to phishing.
In this blog, we are going to give you in detail knowledge about how to sync two versions of MetaMask with each other means how to sync the MetaMask mobile app with the MetaMask chrome extension.
Things that you must have before executing the above-mentioned process:
  1. 1.
    MetaMask chrome extension and its mobile app installed on your phone: You need to have both of them before you start the process of synchronizing them and it will be better if you have done the MetaMask login on both of them.
  2. 2.
    Your secret recovery phrases: To sync the two wallets associated with the two different versions of MetaMask you will need to have the Secret recovery phrase for both of them.
In case, you do not have the secret recovery phrase for the mobile app you can follow the following steps to recover it:
  1. 1.
    Do the MetaMask login and go to settings from the menu of the mobile app.
  2. 2.
    Select “Reveal recovery phrase” from the Security and Privacy section.
  3. 3.
    Enter your password to complete the verification.
Now let us begin with the process of synchronization
The steps for the same are as follows:
  1. 1.
    Initially, you will need to install the extension and activate it.
  2. 2.
    Tap on getting started.
  3. 3.
    Tap on Import wallet.
  4. 4.
    Now, select either “No thanks” or “I agree” on whether you want to share your data or not.
  5. 5.
    Refer to and enter your 12-word secret recovery phrase and make sure that there are spaces between the words. Then, assign a password for the app and click Import.
  6. 6.
    Tap all done and you are done with the process.
In this blog, we have tried to give our best to give you specifically in detail guidance on how to synchronize MetaMask mobile app to the Chrome extension along with the essentials required for executing the process and here the point to remember is that ideally you should do the MetaMask login on both the versions before you implement the given process. We hope this was a helpful and significant blog for you.
Last modified 2mo ago