Build a Authentication Using Blockchain
Last Updated :
23 Jul, 2025
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 [email protected]
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".
Screens folderStep 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
src="https://media.geeksforgeeks.org/wp-content/uploads/20210318103632/gfg.png"
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,
};
Sign in pageStep 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
src="https://media.geeksforgeeks.org/wp-content/uploads/20210318103632/gfg.png"
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 pageStep 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
- Install Metamask extension Ganache.
- First, open Ganache, Click on Quickstart, and 10 addresses with each 100 ETH coins will be visible.
- 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.
- Now open Metamask, Go to settings -> Add networks -> Given below details exactly -> Click on save
Metamask network details Step 5: Working with the Backend
- Create a smart contract which is a main part of Blockchain.
- 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 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 accountOutput:
outputNow Authentication using Blockchain is completed. Check out git repo for full code.
Similar Reads
Solidity Tutorial Solidity tutorial is designed for those who want to learn Solidity programming language and for experienced Solidity developers looking to gain a deeper understanding of the language. The following Solidity tutorial explains the basic and advanced concepts of Solidity programming language and provid
6 min read
Solidity Basics
Introduction to SoliditySolidity is a brand-new programming language created by Ethereum which is the second-largest market of cryptocurrency by capitalization, released in the year 2015 and led by Christian Reitwiessner. Some key features of solidity are listed below: Solidity is a high-level programming language designed
5 min read
Setting Up Smart Contract Development EnvironmentA development environment is an environment in which all the resources and tools are available which are used to develop a program or software product. Here, an attempt to create a development environment that is a collection of the processes and tools that are used to develop smart contracts.There
5 min read
Solidity - Basic SyntaxSolidity is a programming language specifically designed for developing smart contracts on the Ethereum blockchain. It is a high-level, statically-typed language with syntax and features similar to those of JavaScript, C++, and Python. Solidity is used to write self-executing smart contracts that ca
5 min read
"Hello World" Smart Contract in Remix-IDEWhat do you mean by Smart Contract? Smart contracts are self-executing contracts. The term was coined by Nick in 1994. Smart contracts are very different from traditional software programs. They are immutable once deployed on the blockchain. It was because of Ethereum the term smart contract became
4 min read
Solidity - CommentsComments are an important aspect of programming as they help in providing clarity and understanding to the code. They allow developers to document the code and explain its purpose, making it easier for others to read and maintain the code. Solidity, being a programming language, also supports the us
4 min read
Solidity - TypesSolidity is a statically typed language, which implies that the type of each of the variables should be specified. Data types allow the compiler to check the correct usage of the variables. The declared types have some default values called Zero-State, for example for bool the default value is False
4 min read
Variable and Operators
Control Flow in Solidity
Reference & Mapping Types in Solidity
Solidity - StringsSolidity is syntactically similar to JavaScript, C++, and Python. So it uses similar language structures to those languages. Strings in Solidity is a data type used to represent/store a set of characters. Examples: "Hii" // Valid string "Hello World" // Valid string "2022" // Valid string In Solidi
3 min read
Solidity - ArraysArrays are data structures that store the fixed collection of elements of the same data types in which each and every element has a specific location called index. Instead of creating numerous individual variables of the same type, we just declare one array of the required size and store the element
6 min read
Solidity - Enums and StructsEnums are the way of creating user-defined data types, it is usually used to provide names for integral constants which makes the contract better for maintenance and reading. Enums restrict the variable with one of a few predefined values, these values of the enumerated list are called enums. Option
3 min read
Solidity - MappingsMapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type. Mappings are mostly used to associate t
4 min read
Solidity - ConversionsSolidity is a programming language that is used to write smart contracts for the Ethereum blockchain. One important concept in Solidity is conversions, which allow you to change the type of a variable or expression. The article focuses on discussing three types of conversions in Solidity. The follow
6 min read
Solidity - Ether UnitsIn the world of Ethereum smart contracts, understanding how Ether (ETH) and its subunits work is crucial. Solidity is the programming language used to write these smart contracts, and it interacts directly with Ether, the cryptocurrency of the Ethereum network. This article focuses on discussing Eth
7 min read
Solidity - Special VariablesThere exist special variables and functions in solidity which exist in the global namespace and are mainly used to provide information about the blockchain or utility functions. They are of two types: 1) Block and Transaction Properties: Block Transaction Properties block.coinbase (address payable)C
3 min read
Solidity - Style GuideSolidity is a computer programming language used to create Ethereum smart contracts. These contracts self-execute. The code and the agreements contained therein are enforced by the blockchain network. Solidity is a high-level language, meaning that it is designed to be human-readable and easy to wri
13 min read
Solidity Functions
Solidity - FunctionsA function is basically a group of code that can be reused anywhere in the program, which generally saves the excessive use of memory and decreases the runtime of the program. Creating a function reduces the need of writing the same code over and over again. With the help of functions, a program can
4 min read
Solidity - Function ModifiersFunction behavior can be changed using function modifiers. Function modifier can be used to automatically check the condition prior to executing the function. These can be created for many different use cases. Function modifier can be executed before or after the function executes its code. The modi
8 min read
Solidity - View and Pure FunctionsThe view functions are read-only function, which ensures that state variables cannot be modified after calling them. If the statements which modify state variables, emitting events, creating other contracts, using selfdestruct method, transferring ethers via calls, Calling a function which is not 'v
2 min read
Solidity - Fall Back FunctionThe solidity fallback function is executed if none of the other functions match the function identifier or no data was provided with the function call. Only one unnamed function can be assigned to a contract and it is executed whenever the contract receives plain Ether without any data. To receive E
3 min read
Solidity Function OverloadingFunction overloading in Solidity lets you specify numerous functions with the same name but varying argument types and numbers.Solidity searches for a function with the same name and parameter types when you call a function with certain parameters. Calls the matching function. Compilation errors occ
1 min read
Mathematical Operations in SoliditySolidity is a brand-new programming language created by the Ethereum which is the second-largest market of cryptocurrency by capitalization, released in the year 2015 led by Christian Reitwiessner. Ethereum is a decentralized open-source platform based on blockchain domain, used to run smart contrac
6 min read
Solidity Advanced
Solidity - Basics of ContractsSolidity Contracts are like a class in any other object-oriented programming language. They firmly contain data as state variables and functions which can modify these variables. When a function is called on a different instance (contract), the EVM function call happens and the context is switched i
4 min read
Solidity - InheritanceInheritance is one of the most important features of the object-oriented programming language. It is a way of extending the functionality of a program, used to separate the code, reduces the dependency, and increases the re-usability of the existing code. Solidity supports inheritance between smart
6 min read
Solidity - ConstructorsA constructor is a special method in any object-oriented programming language which gets called whenever an object of a class is initialized. It is totally different in case of Solidity, Solidity provides a constructor declaration inside the smart contract and it invokes only once when the contract
4 min read
Solidity - Abstract ContractAbstract contracts are contracts that have at least one function without its implementation or in the case when you don't provide arguments for all of the base contract constructors. Also in the case when we don't intend to create a contract directly we can consider the contract to be abstract. An i
3 min read
Solidity - Basics of InterfaceInterfaces are the same as abstract contracts created by using an interface keyword, also known as a pure abstract contract. Interfaces do not have any definition or any state variables, constructors, or any function with implementation, they only contain function declarations i.e. functions in inte
2 min read
Solidity - LibrariesLibraries in solidity are similar to contracts that contain reusable codes. A library has functions that can be called by other contracts. Deploying a common code by creating a library reduces the gas cost. Functions of the library can be called directly when they do not modify the state variables i
4 min read
Solidity - AssemblyAssembly or Assembler language indicates a low-level programming language that can be converted to machine code by using assembler. Assembly language is tied to either physical or a virtual machine as their implementation is an instruction set, and these instructions tell the CPU to do that fundamen
4 min read
What are Events in Solidity?Solidity Events are the same as events in any other programming language. An event is an inheritable member of the contract, which stores the arguments passed in the transaction logs when emitted. Generally, events are used to inform the calling application about the current state of the contract, w
2 min read
Solidity - Error HandlingSolidity has many functions for error handling. Errors can occur at compile time or runtime. Solidity is compiled to byte code and there a syntax error check happens at compile-time, while runtime errors are difficult to catch and occurs mainly while executing the contracts. Some of the runtime erro
6 min read
Top 50 Solidity Interview Questions and Answers Solidity is an object-oriented programming language used to implement smart contracts on blockchain platforms like Ethereum, which generates transaction records in the system. To excel in your journey toward top companies as a Solidity developer, you need to master some important Solidity Interview
15+ min read