Skip to main content

Telegram Login with Web3Auth

Create a Telegram bot

  1. Follow Telegram's instructions to create a new bot.

  2. 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:

  1. 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.

  2. Create a public key from the private key.

    Run the following command in your terminal:

    openssl rsa -in privateKey.pem -pubout -out publicKey.pem
  3. Convert the public key to JWKS format

    Find a tool that can convert a .pem file to jwk(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}
    • Click on the Convert to JWK button.

      JWKS Convert Tool

  4. 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 the Create Verifier button to create a new verifier.

    Custom Authentication Dashboard

  1. Give a unique name to your verifier in the Verifier Identifier field. e.g., web3auth-telegram-verifier.

  2. From the list of Login Providers, select Custom Providers and enter your JWKS (JSON Web Key Set) endpoint URL in the JWKS Endpoint field.

    e.g., https://your-domain/.well-known/jwks.json

    Create Telegram Verifier on Web3Auth Dashboard

  3. (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.

  4. Select Sub from the dropdown list of JWT Verifier ID.

    Telegram Verifier sub value on Web3Auth Dashboard

  5. Next, click on Add Custom Validation in the Select JWT validation section. Then, input iss in the Field and https://api.telegram.org in the Value field. And click on the Add Validation button.

    Telegram Verifier validation rules on Web3Auth Dashboard

  6. Finally, click on the Create button to create the Telegram Custom Authentication verifier.

    Telegram Verifier on Web3Auth Dashboard

    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.