Telegram Login with Web3Auth
Create a Telegram bot
-
Follow Telegram's instructions to create a new bot.
-
Get the
API Token
from the bot you've created.
Creating a JWKS endpoint
You need to create a JWKS endpoint to verify the JWT token that is generated by your backend server for the Telegram verifier. Each JWT will be signed with the private key. The private key will provide the public key, which will then be converted into a JWKS format.
If you don't have a JWKS endpoint already, you can create one by following these steps:
-
Generate a private key using openssl.
Open your terminal and enter the following command:
openssl genrsa -out privateKey.pem 2048
This
privateKey.pem
file will be used to sign the JWT token. -
Create a public key from the private key.
Run the following command in your terminal:
openssl rsa -in privateKey.pem -pubout -out publicKey.pem
-
Convert the public key to JWKS format
Find a tool that can convert a
.pem
file tojwk(s)
format.-
One such tool is https://pem2jwk.vercel.app
- Select the Signing Algorithm as
RS256
- Select Public Key Use as
Signing
- Key ID:
paste-yours
or leave it blank to generate a random one. - PEM encoded key:
{paste-the-publicKey-pem-file-s-content-here}
- Select the Signing Algorithm as
-
Click on the
Convert to JWK
button.
-
-
Create a
jwks.json
file using the output and host it on your server to ensure it's publicly accessible. Alternatively, you can create a JWKS endpoint using the following code:const express = require("express");
const fs = require("fs");
const { resolve } = require("path");
const app = express();
app.get("/.well-known/jwks.json", (req, res) => {
res.sendFile(resolve(__dirname, "jwks.json"));
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});The
jwks.json
file will look something like this:{
"kty": "RSA",
"n": "uCCj0ZgH9nL....MbVZZ21Xp....TjSJr",
"e": "AQAB",
"ext": true,
"kid": "e015e03692f2e1c79030b", // Key ID
"alg": "RS256",
"use": "sig"
}Your JWKS endpoint will look something like
https://your-domain/.well-known/jwks.json
.
Create a Telegram verifier
-
Go to the Web3Auth dashboard and select your project. Click on the
Custom Authentication
tab, then click on theCreate Verifier
button to create a new verifier.
-
Give a unique name to your verifier in the
Verifier Identifier
field. e.g.,web3auth-telegram-verifier
. -
From the list of Login Providers, select
Custom Providers
and enter your JWKS (JSON Web Key Set) endpoint URL in theJWKS Endpoint
field.e.g.,
https://your-domain/.well-known/jwks.json
-
(Optional) If you have already created the backend server that generates the JWT token using Telegram's user data, you can paste a sample JWT token in the
Paste a JWT Token here
field. This is optional, but it helps you select the correct JWT validation rules. -
Select
Sub
from the dropdown list ofJWT Verifier ID
. -
Next, click on
Add Custom Validation
in theSelect JWT validation
section. Then, inputiss
in the Field andhttps://api.telegram.org
in the Value field. And click on theAdd Validation
button. -
Finally, click on the
Create
button to create the Telegram Custom Authentication verifier.It typically takes 5-10 minutes for the verifier to go live. Once deployed & live, you'll receive an email and the dashboard will display the 'Live' status for the verifier.
Example
import { Web3AuthNoModal } from "@web3auth/no-modal";
import { WALLET_ADAPTERS, CHAIN_NAMESPACES, UX_MODE, WEB3AUTH_NETWORK } from "@web3auth/base";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { AuthAdapter } from "@web3auth/auth-adapter";
const clientId =
"BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ";
// get it from https://dashboard.web3auth.io by creating a project.
const chainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth",
displayName: "Ethereum Mainnet",
blockExplorerUrl: "https://etherscan.io",
ticker: "ETH",
tickerName: "Ethereum",
logo: "https://images.toruswallet.io/ethereum.svg",
};
const privateKeyProvider = new EthereumPrivateKeyProvider({
config: { chainConfig },
});
const web3auth = new Web3AuthNoModal({
clientId,
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
privateKeyProvider: privateKeyProvider,
});
const authAdapter = new AuthAdapter({
adapterSettings: {
uxMode: UX_MODE.REDIRECT,
loginConfig: {
jwt: {
verifier: "web3auth-telegram-example", // Pass the Verifier name here
typeOfLogin: "jwt", // Pass on the login provider of the verifier you've created
clientId,
},
},
},
});
web3auth.configureAdapter(authAdapter);
setWeb3auth(web3auth);
// Initialize
await web3auth.init();
// Initiate the login using Telegram Widget
const login = async () => {
const URL = "https://your-domain";
window.location.href = `${URL}/login`;
};
// Catch the JWT token from the backend server and pass it to the Web3Auth SDK
// Preferably, in a useEffect hook or a callback function
const params = new URLSearchParams(window.location.search);
const idToken = params.get("token");
// To know more about how to generate the JWT token, refer to the linked guide.
// Login with Telegram with Web3Auth using received JWT token
await web3auth.connectTo(WALLET_ADAPTERS.AUTH, {
loginProvider: "jwt",
extraLoginOptions: {
id_token: idToken, // Received from the backend server
verifierIdField: "sub",
},
});
Questions?
If you have any questions or need assistance, please don't hesitate to contact us via posting in this thread on our Community Forum.