The Wayback Machine - https://web.archive.org/web/20240903002516/https://www.geeksforgeeks.org/build-a-authentication-using-blockchain/
Open In App

Build a Authentication Using Blockchain

Last Updated : 25 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Normally authentication is seen using databases like MYSQL, Firebase, MongoDB, etc. One of the biggest drawbacks is the chance of the data getting corrupted. The data can be modified by anyone who is in control of the database itself.
To overcome the above problem here a web app authentication using blockchain will be created.

Components in Web Authentication Application:

  • Ganache: A local Ethereum blockchain.
  • Web3 JS: For the application to be able to communicate to the blockchain.
  • Solidity: For compilation smart contract.
  • React JS: For the application’s front-end.
  • Truffle: For a development environment, asset pipeline, and testing framework for developing smart contracts.
  • Metamask: For cryptocurrency wallet.

Step 1: Truffle Installation globally 

 Open your command prompt and install truffle using the below command:

npm install -g truffle@5.4.29

Step 2: React app installation

Follow the below steps to create the application:

npx create-react-app auth-app
cd auth-app

Now install all required modules for the project by using the below command:

npm install react-router-dom web3

Step 3: Working with frontend

Step 3.1: Open the “src” folder and select the App.js file. 

This file contains routing logic, where routing helps the user to navigate different pages. Go through react-router-dom documentation to understand more about routing in React JS.

Below is the code for App.js file:

Javascript




import "./App.css";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import SignIn from "./Screens/Signin";
import SignUp from "./Screens/Signup";
import Home from "./Screens/Home";
 
function App() {
  const email = localStorage.getItem("email");
  return (
    <div className="App">
      <BrowserRouter>
        <Routes>
          <Route exact path="/" element={<SignIn />} />
          <Route path="/Signup" element={<SignUp />} />
          <Route
            path="/Home"
            element={email ? <Home /> : <Navigate to="/" />}
          />
        </Routes>
      </BrowserRouter>
    </div>
  );
}
 
export default App;


Step 3.2: Create the “Screens” folder and Create files “Signin.js”, “Signup.js”, “Home.js”.

Create files "Signin.js", "Signup.js", "Home.js"

Screens folder

Step 3.3: Working with the Signin.js file 

Here users need to enter their email and password. Below code authenticates the user’s input email and password and navigates to the home page:

Javascript




// calling smart contract map methods
const res = await auth.methods.usersList(email).call();
        
// In res the is username , password and email
// checking input password with stored password
if (res.password === password)
{   
     
    // storing user details in local storage
    localStorage.setItem("email", email);
         
    localStorage.setItem("account", accounts);
    navigate("/Home"); // navigate to home page
}
else
{
    alert("wrong user credentials or please signup");
}


1. If the user is not registered give an alert as the user is not found.

2. If the user entered the wrong credentials give an alert as the wrong password.

After Sign in success, users navigate to the home page

Signin.js: 

Javascript




import * as React from "react";
import { loadBlockchainData, loadWeb3 } from "../Web3helpers";
import { useNavigate } from "react-router-dom";
 
export default function SignIn() {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const navigate = useNavigate();
 
  const [accounts, setAccounts] = React.useState(null);
  const [auth, setAuth] = React.useState(null);
 
  const loadAccounts = async () => {
    let { auth, accounts } = await loadBlockchainData();
 
    setAccounts(accounts);
    setAuth(auth);
  };
 
  const login = async () => {
    if (!email || !password) {
      alert("please fill all details");
 
      return;
    }
 
    try {
      const res = await auth.methods.usersList(email).call();
 
      if (res.password === password) {
        localStorage.setItem("email", email);
        localStorage.setItem("account", accounts);
        navigate("/Home");
      } else {
        alert("wrong user credentials or please signup");
      }
    } catch (error) {
      alert(error.message);
    }
  };
 
  React.useEffect(() => {
    loadWeb3();
  }, []);
 
  React.useEffect(() => {
    loadAccounts();
  }, []);
 
  return (
    <div style={rootDiv}>
      <img
        style={image}
        alt="geeks"
      />
      <input
        style={input}
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
        type="text"
      />
      <input
        style={input}
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
        type="password"
      />
      <button style={button} onClick={login}>
        {" "}
        Sign In
      </button>
 
      <span
        style={{ cursor: "pointer" }}
        onClick={() => {
          navigate("/Signup");
        }}
      >
        {" "}
        Create new account{" "}
      </span>
    </div>
  );
}
 
const rootDiv = {
  display: "flex",
  flexDirection: "column",
  alignItems: "center",
  justifyContent: "center",
  height: "100vh",
};
 
const input = {
  width: 300,
  padding: 10,
  margin: 10,
  borderRadius: 10,
  outline: "none",
  border: "2px solid grey",
  fontSize: 17,
};
 
const button = {
  width: 325,
  padding: 10,
  borderRadius: 10,
  margin: 10,
  cursor: "pointer",
  fontSize: 17,
  color: "white",
  backgroundColor: "#9D27CD",
  border: "none",
};
 
const image = {
  width: 70,
  height: 70,
  objectFit: "contain",
  borderRadius: 70,
};


Singin.js

Sign in page

Step 3.4: Working with the Signup.js file

Here users need to Register/Signup with a username, email, and password. Below code creates a new user in the blockchain database 

await auth.methods
.createUser(username, email, password)
.send({ from: accounts });

After Registration, the user navigates to the Sign-in page.

Signup.js

Javascript




import * as React from "react";
import { loadBlockchainData, loadWeb3 } from "../Web3helpers";
 
import { useNavigate } from "react-router-dom";
export default function SignUp() {
  const [username, setUsername] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
 
  const navigate = useNavigate();
 
  const [accounts, setAccounts] = React.useState(null);
  const [auth, setAuth] = React.useState(null);
 
  const loadAccounts = async () => {
    let { auth, accounts } = await loadBlockchainData();
 
    setAccounts(accounts);
    setAuth(auth);
  };
 
  const signUp = async () => {
    if (!username || !email || !password) {
      alert("please fill all details");
      return;
    }
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if (!email.match(mailformat)) {
      alert("please enter valid email address");
      return;
    }
    try {
      await auth.methods
        .createUser(username, email, password)
        .send({ from: accounts });
 
      localStorage.setItem("username", username);
      localStorage.setItem("email", email);
      navigate("/");
    } catch (e) {
      console.log(e.message);
    }
  };
  React.useEffect(() => {
    loadWeb3();
  }, []);
 
  React.useEffect(() => {
    loadAccounts();
  }, []);
 
  return (
    <div style={rootDiv}>
      <img
        style={image}
        alt="geeks"
      />
      <input
        style={input}
        value={username}
        onChange={(e) => setUsername(e.target.value)}
        placeholder="Username"
        type="text"
      />
      <input
        style={input}
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
        type="text"
      />
      <input
        style={input}
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
        type="password"
      />
      <button style={button} onClick={signUp}>
        {" "}
        Sign Up
      </button>
    </div>
  );
}
 
const rootDiv = {
  display: "flex",
  flexDirection: "column",
  alignItems: "center",
  justifyContent: "center",
  height: "100vh",
};
 
const input = {
  width: 300,
  padding: 10,
  margin: 10,
  borderRadius: 10,
  outline: "none",
  border: "2px solid grey",
  fontSize: 17,
};
 
const button = {
  width: 325,
  padding: 10,
  borderRadius: 10,
  margin: 10,
  cursor: "pointer",
  fontSize: 17,
  color: "white",
  backgroundColor: "#9D27CD",
  border: "none",
};
 
const image = {
  width: 70,
  height: 70,
  objectFit: "contain",
  borderRadius: 70,
};


Sign up page

Sign Up page

Step 3.5: Working with the Home.js file

Here we find the user address and email 

Home.js

Javascript




import React from "react";
import { useNavigate } from "react-router-dom";
 
export default function Home() {
  const email = localStorage.getItem("email");
  const account = localStorage.getItem("account");
 
  const navigate = useNavigate();
  return (
    <div>
      <h3>Your account: {account} </h3>
      <h3>Your email: {email} </h3>
      <button
        style={button}
        onClick={() => {
          localStorage.removeItem("email");
          localStorage.removeItem("account");
          window.location.reload();
        }}
      >
        {" "}
        Log out
      </button>
    </div>
  );
}
const button = {
  width: 100,
  padding: 10,
  borderRadius: 5,
  margin: 10,
  cursor: "pointer",
  fontSize: 17,
  color: "white",
  backgroundColor: "#9D27CD",
  border: "none",
};


Step 3.6: Now create Web3helpers.js file in the src folder, to store web3 functions used for loading address from Metamask. Below is the code for Web3helpers.js file:

Javascript




import Web3 from "web3/dist/web3.min.js";
 
import Auth from "./build/contracts/Auth.json";
 
export const loadWeb3 = async () => {
  if (window.ethereum) {
    window.web3 = new Web3(window.ethereum);
    await window.ethereum.enable();
  } else if (window.web3) {
    window.web3 = new Web3(window.web3.currentProvider);
  } else {
    window.alert(
      "Non-Ethereum browser detected. You should consider trying MetaMask!"
    );
  }
};
 
export const loadBlockchainData = async () => {
  const web3 = window.web3;
  // Load account
  const accounts = await web3.eth.getAccounts();
 
  // Network ID
 
   
 
  const networkId = await web3.eth.net.getId();
 
  
  // Network data
 
  if (networkId) {
    const auth = new web3.eth.Contract(
      Auth.abi,
      Auth.networks[networkId].address
    );
    return { auth, accounts: accounts[0] };
  }
};


Step 4 : Setting up Metamask and Ganache 

  1. Install Metamask extension Ganache. 
  2. First, open Ganache, Click on Quickstart, and 10 addresses with each 100 ETH coins will be visible.
  3. On top, one would be able to see Network id as 1337 and RPC server as HTTP://127.0.0.1:7545, if there are different id and server, go to settings, change them, and click on save, and restart.
  4. Now open Metamask, Go to settings -> Add networks -> Given below details exactly -> Click on save
Setting up Metamask

Metamask network details

 Step 5: Working with the Backend 

  1.  Create a smart contract which is a main part of Blockchain.
  2.  Now open the command line -> Go to your auth-app (frontend) -> Apply the below commands.
cd src
truffle build

Now you are able to see folders “migrations”, “contracts”, and “build” in the src folder.

Step 5.1: Open the migrations folder and create a Javascript file as 2_deploy_migration.js.

Here we are deploying our smart contract that we are going to create 

2_deploy_migration.js:

Javascript




const Auth = artifacts.require("Auth");
 
module.exports = function (deployer) {
  deployer.deploy(Auth);
};


Step 5.2: Open the contracts folder and create a solidity file as “Auth.sol”.

Here a smart contract will be created for our authentication. Below is the code for defining a map with a struct:

 mapping(string => user) public usersList;

     struct user{
      string username;
      string email;
      string password;
  }

The below function takes parameters of the user’s email, password, and username and maps user details to the user email:

function createUser(string memory _username,
                    string memory _email,
                    string memory _password) public 
{      
    userCount++;
    usersList[_email] = user(_username,_email,_password);      
    emit userCreated(_username,_email,_password);
}

Auth.sol: 

Solidity




// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
 
contract Auth
{   
    uint public userCount = 0;
 
    mapping(string => user) public usersList;
 
     struct user
     {
       string username;
       string email;
       string password;
     }
 
   // events
 
   event userCreated(
      string username,
      string email,
      string password
    );
 
  function createUser(string memory _username,
                      string memory _email,
                      string memory _password) public
  {     
      userCount++;
      usersList[_email] = user(_username,
                               _email,
                               _password);
      emit userCreated(_username,
                       _email,
                       _password);
    }
}


Step 6: Apply the below command it will create a contract address:

truffle migrate --reset
Contract Address

contract address 

Step 7: Adding accounts to Metamask from ganache

  • Open Ganache, click on the key icon of any address copy the private key.
  • Open Metamask -> select ganache network ->  Click on profile (right top) -> Click on import account -> paste the copied private key.
  • Now you are able to see 100 ETH coins in your account.

Step 8: Running and Building the application: We can run this application by using the following command. This will start React’s development server that can be used for debugging our application.

npm run start
  • Once the webpage opens connect your Metamask account.
  • Click on “Not connected” and it will connect.
Connect account

Connect account

Output:

Output video

output

Now Authentication using Blockchain is completed. Check out git repo for full code.



Previous Article
Next Article

Similar Reads

What is Blockchain Authentication?
Blockchain is a digital decentralized public ledger designed to record every data exchange on its network. Therefore for the security of data exchange on the network, blockchain flow's a process that verifies a user with distributed ledger and also verifies the digital identity of the user at the same time to protect the passwords and data of the u
6 min read
Blockchain - Data Origin Authentication
Blockchain is a technology that is being used in more and more businesses around the world, from financial services to healthcare. It offers a level of security that provides protection for data not only for the business owner but also for clients who will be accessing their data. blockchain has been developed to provide heightened protection over
8 min read
Build a To-do List Web Application Powered by Blockchain
Here, we are going to build a to-do list application that will save the data in the blockchain. The blockchain part of this application can also be understood as a database. First, we'll create a smart contract and subsequently the web application itself. We'll use Bloc as the application name but first, let's look at the components. Components in
15 min read
Create simple Blockchain using Python
Blockchain is a time-stamped decentralized series of fixed records that contains data of any size is controlled by a large network of computers that are scattered around the globe and not owned by a single organization. Every block is secured and connected with each other using hashing technology which protects it from being tampered by an unauthor
8 min read
Decentralized Voting System using Blockchain
Blockchain is a technology that is rapidly gaining momentum in era of industry 4.0. With high security and transparency provisions, it is being widely used in supply chain management systems, healthcare, payments, business, IoT, voting systems, etc. Why do we need it? Current voting systems like ballot box voting or electronic voting suffer from va
4 min read
How to deploy Smart Contracts using Ethers.js and Node.js on Goerli Testnet Blockchain from Back-end ?
In this article, we will be deploying smart contracts on blockchain from back-end, so that we do not have to require hardhat or truffle frameworks and their commands to deploy a smart contract or if somebody doesn't want to use these frameworks. Since we have to run manual commands of these frameworks in the terminal to deploy Smart Contracts. We c
9 min read
Blockchain - Creating Elliptic Curve Keys using OpenSSL
Elliptic curve cryptography is employed to implement public key cryptography. It had been discovered by Victor Miller of IBM and Neal Koblitz of the University of Washington in 1985. ECC, popularly utilized, is an acronym for Elliptic Curve Cryptography. It's grounded on recent mathematics and delivers a reasonably more secure foundation than the f
3 min read
Blockchain - Encrypt & Decrypt Files With Password Using OpenSSL
Encryption is the process of encoding information or data in such a way that only authorized parties can access it. The process of encrypting information involves using a mathematical algorithm to transform the original information, known as plaintext, into a form that is unreadable to anyone who does not have the means to decrypt it, known as ciph
5 min read
Flutter and Blockchain - Hello World Dapp
This tutorial will take you through the process of building your first mobile dapp - Hello World Dapp! This tutorial is meant for those with a basic knowledge of Ethereum and smart contracts, who have some knowledge of the Flutter framework but are new to mobile dapps. In this tutorial we will be covering: Setting up the development environmentCrea
9 min read
Integration of Artificial Intelligence and BlockChain
Artificial Intelligence and Blockchain are proving to be quite a powerful combination, improving virtually every industry in which they're implemented. These technologies can be combined to upgrade everything from food supply chain logistics and healthcare record sharing to media royalties and financial security. The integration of AI and Blockchai
8 min read
How to use GANACHE Truffle Suite to Deploy a Smart Contract in Solidity (Blockchain)?
There are various processes involved in deploying a smart contract using Ganache and Truffle Suite: 1. Install Ganache first. Ganache is a personal blockchain for Ethereum development. You must first download and install it. It is available for download from https://www.trufflesuite.com/ganache, the official website. 2. Install Truffle Suite: The n
4 min read
Introduction to Blockchain technology | Set 2
Blockchain technology has been garnering great hype recently. It gained popularity after the introduction of Bitcoin in 2009 by the person or group of people by the pseudonym Satoshi Nakamoto. Many people confuse and believe blockchain to be bitcoin. But, bitcoin is one application of the blockchain technology. There are many other applications and
5 min read
What is Blockchain Wallet?
A blockchain wallet is a software that enables sending and receiving cryptocurrencies such as Bitcoin, Ethereum, etc. It stores the record of transactions and also public and private keys which are used to perform transactions. A public key is similar to an account number. If A wants to send some money to B using Bitcoin when A sends the public key
10 min read
What is Consortium Blockchain?
A consortium blockchain is a group of multiple financial institutions where each financial institution has its private blockchain. In this blockchain, a pre-selected set of nodes are allowed to control the consensus process. What is Consortium Blockchain?Consortium blockchains are managed and run by a number of organizations or entities. As a permi
9 min read
Blockchain - Proof of Work (PoW)
Proof of Work consensus is the mechanism of choice for the majority of cryptocurrencies currently in circulation. The algorithm is used to verify the transaction and create a new block in the blockchain. The idea for Proof of Work(PoW) was first published in 1993 by Cynthia Dwork and Moni Naor and was later applied by Satoshi Nakamoto in the Bitcoi
6 min read
Benefits of Blockchain Technology
Blockchain is the backbone Technology of Digital CryptoCurrency BitCoin. Blockchain technology is a digital or ledger technology that evaluates the records and makes track of it in a peer-to-peer network. Each transaction is verified by the majority of participants of the system. It contains every single record of each transaction. Benefits of Bloc
5 min read
Blockchain and Data Privacy
Blockchain has been defined as a digital, decentralized ledger that keeps a record of all transactions that take place across a peer-to-peer network. It enables the secure transfer of assets without an intermediary. It also provides a record of transactions that is fully transparent and displayed in real-time for benefit of participants. Blockchain
11 min read
7 Project Ideas on Blockchain For Professionals
We have passed the time when blockchain was used only in the form of cryptocurrency. Today, it is being used in a broader domain and it's going to dominate in the coming future. As per the latest reports, it is expected that corporations will spend around $20 Billion on blockchain technical services by 2024. Industries like Healthcare, Insurance, I
8 min read
Consensus Algorithms in Blockchain
Prerequisites: Introduction to Blockchain technology | Set 1, Set 2 We know that Blockchain is a distributed decentralized network that provides immutability, privacy, security, and transparency. There is no central authority present to validate and verify the transactions, yet every transaction in the Blockchain is considered to be completely secu
5 min read
Blockchain to Secure IoT Data
INTRODUCTION: Internet of things and Blockchain are two technologies which are gaining popularity since the time of their creation. In the near future, IoT is going to influence almost every day-to-day items we use. As the usage of this technology increases, the threat to misuse it also increases. Existing technologies are not enough to deal with t
7 min read
Difference between Blockchain and a Database
Database: Generally a database is a data structure which is used for storing information. It is a organised collection or storage of data which is able to store a new data or access a existing data. The data stored in a database can be organized using a database management system. The database administrator can modify the data stored in the databas
2 min read
What Are Cryptoasssets in Blockchain
So as you are aware of Blockchain technology and have of the basic idea of it, in this article we will be talking about the cryptocurrency part of the blockchain, more specifically about the crypto-assets. As we know, an asset is something that holds value, similarly, a crypto-asset is an asset that is based on cryptography. Mostly it is a virtual
3 min read
Basics of the Blockchain and its various applications
The BlockChain, to begin with is undeniably one of the most ingenious inventions of mankind. Considering it to be the brainchild the pseudonym, Satoshi Nakamoto, the technology has evolved into something unimaginably great. However, the most commonly asked always arises every single time - What is this Blockchain? A BlockChain is defined as a peer
5 min read
Proof of Stake (PoS) in Blockchain
Proof of Stake (PoS) is a type of algorithm which aims to achieve distributed consensus in a Blockchain. This way to achieve consensus was first suggested by Quantum Mechanic here and later Sunny King and his peer wrote a paper on it. This led to Proof-of-Stake (PoS) based Peercoin. A stake is value/money we bet on a certain outcome. The process is
5 min read
How Block Hashes Work in Blockchain?
Blockchain is the backbone technology of the digital cryptocurrency Bitcoin. The blockchain is a distributed database of records of all transactions or digital events that have been executed and shared among participating parties. Each transaction is verified by the majority of participants of the system. It contains every single record of each tra
7 min read
Features of Blockchain
Here In this article, we will discuss the features of blockchain technology and how they make it a revolutionary and highly desirable platform for various applications. A blockchain is a chain of blocks that contains information. Most people think that Blockchain is Bitcoin and vice-versa. But it’s not the case. In fact, Bitcoin is a digital curren
7 min read
How does BlockChain support Crowdfunding ?
The Crowdfunding platform in block-chain makes different possibilities for the startups by raising the funds to create their own digital currency and it is peer-to-peer fund raising model some of the famous crowdfunding cryptocurrencies are coinspace, swarm, judobaby etc. Crowdfunding has offers for creators and other consumers. Anyone can particip
2 min read
Demur-rage currencies in Blockchain
Currency is one such core concept in blockchain technology that can extended and re-understood. Currency which is usually referred as digital token it facilitates quantified transfer mechanism. This idea is known as Demur-rage currency. Demur-rage means "cost of carrying"- that is the cost to carry an asset. The Demur-rage originated from freight a
2 min read
Blockchain Gaming : Part 1 (Introduction)
Blockchain Gaming. It’s a world of it’s own. It’s ‘Ready Player One’ incorporated into gaming. Before reading this article, it is recommended to read: Introduction to Blockchain to get well versed with the concept of blockchain. Part-1: Transparency, Proven Rarity and True Ownership Transparency: When games use third party distribution platforms li
4 min read
Blockchain Hash Function
A hash function is a mathematical function that takes an input string of any length and converts it to a fixed-length output string. The fixed-length output is known as the hash value. To be cryptographically secure and useful, a hash function should have the following properties: Collision resistant: Give two messages m1 and m2, it is difficult to
5 min read
Article Tags :