Issue with Setting Up Single Factor Authentication (SFA): Unknown Host Error

Issue with Setting Up Single Factor Authentication (SFA): Unknown Host Error

Hi,

I’m facing an issue while setting up Single Factor Authentication (SFA) in my application. I followed the documentation and created the app in OAuth, adding https://auth.web3auth.io/auth as allowed callback url.

However, when I click the Login button, I am getting the following error: Unknown Host Error for oauth_domain_id in my browser. I’ve attached a screenshot of the issue for reference.



package.json

{
  "name": "auth_web_app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@auth0/auth0-react": "^2.2.4",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@web3auth/base": "^9.0.2",
    "@web3auth/ethereum-provider": "^9.0.2",
    "@web3auth/modal": "^9.1.0",
    "@web3auth/openlogin-adapter": "^8.12.4",
    "@web3auth/single-factor-auth": "^9.0.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "buffer": "^6.0.3",
    "process": "^0.11.10",
    "react-app-rewired": "^2.2.1"
  }
}

index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Auth0Provider } from "@auth0/auth0-react";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Auth0Provider
      domain="oauth_domain_id"
      clientId="oauth_client_id"
      authorizationParams={{
        redirect_uri: window.location.origin,
        connection: "google",
      }}
    >
      <App />
    </Auth0Provider>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

App.js

import { useEffect, useRef, useState } from "react";
import { Web3Auth, decodeToken } from "@web3auth/single-factor-auth";
import { CHAIN_NAMESPACES, WEB3AUTH_NETWORK } from "@web3auth/base";
import { CommonPrivateKeyProvider } from "@web3auth/base-provider";
import { useAuth0 } from "@auth0/auth0-react";

import "./App.css";

const verifier = "w3a-a0-github-demo";
const clientId =
  "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ"; // get from https://dashboard.web3auth.io

const chainConfig = {
  chainNamespace: CHAIN_NAMESPACES.EIP155,
  chainId: "0x14A34", // hex of 84532
  rpcTarget: "https://sepolia.base.org",
  // Avoid using public rpcTarget in production.
  // Use services like Infura, Quicknode etc
  displayName: "Base Sepolia",
  blockExplorerUrl: "https://sepolia-explorer.base.org",
  ticker: "ETH",
  tickerName: "ETH",
  logo: "https://github.com/base-org/brand-kit/blob/main/logo/symbol/Base_Symbol_Blue.svg",
};

const privateKeyProvider = new CommonPrivateKeyProvider({
  config: { chainConfig },
});

const web3authSfa = new Web3Auth({
  clientId, // Get your Client ID from Web3Auth Dashboard
  web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
  usePnPKey: false, // Setting this to true returns the same key as PnP Web SDK, By default, this SDK returns CoreKitKey.
  privateKeyProvider,
});
const TonRPC = {};

function App() {
  const [isLoggingIn, setIsLoggingIn] = useState(false);
  const [loggedIn, setLoggedIn] = useState(false);
  const {
    isAuthenticated,
    isLoading,
    getIdTokenClaims,
    loginWithRedirect,
    logout: auth0Logout,
  } = useAuth0();
  const [provider, setProvider] = useState(null);

  useEffect(() => {
    const init = async () => {
      try {
        await web3authSfa.init();

        if (web3authSfa.status === "connected") {
          setLoggedIn(true);
          setProvider(web3authSfa.provider);
        }
      } catch (error) {
        console.error("Error during Web3Auth initialization:", error);
      }
    };

    init();
  }, []);

  useEffect(() => {
    const connectWeb3Auth = async () => {
      if (isAuthenticated && !loggedIn && web3authSfa.status === "ready") {
        try {
          setIsLoggingIn(true);
          const idToken = (await getIdTokenClaims())?.__raw;
          console.log("id  toke ", idToken);
          if (!idToken) {
            console.error("No ID token found");
            return;
          }
          const { payload } = decodeToken(idToken);
          await web3authSfa.connect({
            verifier,
            verifierId: payload.sub,
            idToken: idToken,
          });
          setIsLoggingIn(false);
          setLoggedIn(true);
          setProvider(web3authSfa.provider);
        } catch (err) {
          setIsLoggingIn(false);
          console.error("Error during Web3Auth connection:", err);
        }
      }
    };

    connectWeb3Auth();
  }, [isAuthenticated, loggedIn, getIdTokenClaims]);

  const login = async () => {
    if (!web3authSfa) {
      uiConsole("Web3Auth Single Factor Auth SDK not initialized yet");
      return;
    }
    if (web3authSfa.status === "not_ready") {
      await web3authSfa.init();
    }
    await loginWithRedirect();
  };

  const getUserInfo = async () => {
    if (!provider) {
      uiConsole("Web3Auth Single Factor Auth SDK not initialized yet");
      return;
    }
    const userInfo = await web3authSfa.getUserInfo();
    uiConsole(userInfo);
  };

  const logout = async () => {
    if (!provider) {
      uiConsole("Web3Auth Single Factor Auth SDK not initialized yet");
      return;
    }
    await web3authSfa.logout();
    setLoggedIn(false);
    setProvider(null);
    auth0Logout({ logoutParams: { returnTo: window.location.origin } });
  };

  const getAccounts = async () => {
    if (!provider) {
      uiConsole("No provider found");
      return;
    }
    const rpc = new TonRPC(web3authSfa.provider);
    const userAccount = await rpc.getAccounts();
    uiConsole(userAccount);
  };

  const getBalance = async () => {
    if (!provider) {
      uiConsole("No provider found");
      return;
    }
    const rpc = new TonRPC(web3authSfa.provider);
    const balance = await rpc.getBalance();
    uiConsole(balance);
  };

  const signMessage = async () => {
    if (!provider) {
      uiConsole("No provider found");
      return;
    }
    const rpc = new TonRPC(web3authSfa.provider);
    const result = await rpc.signMessage("Hello, TON!");
    uiConsole(`Message signed. Signature: ${result}`);
  };

  const sendTransaction = async () => {
    if (!provider) {
      uiConsole("No provider found");
      return;
    }
    const rpc = new TonRPC(web3authSfa.provider);
    const result = await rpc.sendTransaction();
    uiConsole(result);
  };

  const authenticateUser = async () => {
    if (!provider) {
      uiConsole("No provider found");
      return;
    }
    const userCredential = await web3authSfa.authenticateUser();
    uiConsole(userCredential);
  };

  const getPrivateKey = async () => {
    if (!web3authSfa.provider) {
      uiConsole("No provider found");
      return "";
    }
    const rpc = new TonRPC(web3authSfa.provider);
    const privateKey = await rpc.getPrivateKey();
    return privateKey;
  };

  function uiConsole(...args) {
    const el = document.querySelector("#console>p");
    if (el) {
      el.innerHTML = JSON.stringify(args || {}, null, 2);
    }
  }

  const loginView = (
    <>
      <div className="flex-container">
        <div>
          <button onClick={getUserInfo} className="card">
            Get User Info
          </button>
        </div>
        <div>
          <button onClick={authenticateUser} className="card">
            Authenticate User
          </button>
        </div>
        <div>
          <button onClick={getAccounts} className="card">
            Get Accounts
          </button>
        </div>
        <div>
          <button onClick={getBalance} className="card">
            Get Balance
          </button>
        </div>
        <div>
          <button onClick={signMessage} className="card">
            Sign Message
          </button>
        </div>
        <div>
          <button onClick={sendTransaction} className="card">
            Send Transaction
          </button>
        </div>
        <div>
          <button onClick={getPrivateKey} className="card">
            Get Private Key
          </button>
        </div>
        <div>
          <button onClick={logout} className="card">
            Log Out
          </button>
        </div>
      </div>

      <div id="console" style={{ whiteSpace: "pre-line" }}>
        <p style={{ whiteSpace: "pre-line" }}></p>
      </div>
    </>
  );

  const logoutView = (
    <button onClick={login} className="card">
      Login
    </button>
  );

  return (
    <div className="container">
      <h1 className="title">
        <a
          target="_blank"
          href="https://web3auth.io/docs/sdk/core-kit/sfa-web"
          rel="noreferrer"
        >
          Web3Auth
        </a>{" "}
        SFA React Ton GitHub Example
      </h1>

      {isLoading || isLoggingIn ? null : (
        <div className="grid">
          {web3authSfa ? (loggedIn ? loginView : logoutView) : null}
        </div>
      )}

      <footer className="footer">
        <a
          href="https://github.com/Web3Auth/web3auth-core-kit-examples/tree/main/single-factor-auth-web/sfa-web-ton-telegram-example"
          target="_blank"
          rel="noopener noreferrer"
        >
          Source code
        </a>
      </footer>
    </div>
  );
}

export default App;

Could someone guide me on what might be going wrong? Any help or insights would be greatly appreciated!

Hi Tech Plena,

Thank you for reaching out. From your description and the provided code snippets, I see you’re encountering an Unknown Host Error when setting up Single Factor Authentication (SFA) with Web3Auth.

Summary of the Issue

  • Error: Unknown Host Error for project_domain_url
  • SDK Details: Web3Auth Single Factor Authentication
  • SDK Version: @web3auth/single-factor-auth:^9.0.0
  • Platform: React (potentially web-based)

Key Details:

  • Initialisation & Login Code Snippets: Provided in App.js
  • OAuth Setup: Callback URL https://auth.web3auth.io/auth seems to be correctly set.

Observations:

  1. Callback URL Configuration: Ensure the exact callback URL configured on OAuth settings matches the one used in your application. Also, double-check that the OAuth domain and client ID are set correctly.
  2. Domain Whitelisting: Verify that project_domain_url (your actual project’s domain) is correctly whitelisted in the Web3Auth dashboard.
  3. CORS Issues: Sometimes, such errors arise from misconfiguration of CORS policies on the backend.

Requested Information:

  1. Console Output: Could you provide a more detailed browser console log, especially the network request details that might give more context to the “Unknown Host Error”?
  2. OAuth Settings Validation:
    • Double-check the OAuth domain and client ID in your Auth0Provider configuration.
    • Ensure that connection: "google" is a valid connection configured in Auth0 and linked correctly to your Web3Auth setup.
  3. Initialization Related: Scrutinize your Web3Auth initialization for any overlooked details.

If you can provide these additional details, it will allow the support team to assist you more effectively.


This response was generated by the Web3Auth Bot. A member of the Web3Auth team will review your query and provide further assistance.

Hey @tech7

Please check that the clientId and domain in your Auth0Provider match the values from your Auth0 dashboard (e.g., your-domain.auth0.com and your actual client ID). Also, verify that the verifier w3a-a0-github-demo includes your Auth0 domain and is correctly configured in the Web3Auth dashboard.

Assuming you’ve replaced the placeholders (oauth_domain_id, oauth_client_id) with actual values, double-check for any discrepancies.

Let us know if this resolves the issue!

hey @maharshi , how do I configure the w3a-a0-github-demo verifier in my Web3Auth dashboard?

Hey @tech7,

It seems you’re using the verifier from our demo, correct? Web3Auth needs to ensure that the redirection for Auth0 login is legitimate by whitelisting the specific Auth0 client ID and domain. The verifier you’re using from the example app is configured with the Auth0 client ID and domain from our demo, which means it only works for that setup and disallows any other client ID or domain, including yours.

To resolve this:

  1. Go to the Web3Auth Dashboard, create a new project either on sapphire_mainnet or sapphire_devnet.
  2. Create a new verifier for your Auth0 login by following these steps under the “Setup your Web3Auth Dashboard” section.
  3. Once the verifier is created, pass it’s name along with the Web3Auth project client ID into the Web3Auth constructor in your code. Please check if the web3AuthNetwork in your code matches with the one on your dashboard.

This should fix the issue.

Hey @maharshi , I followed all the steps, created a new verifier, and updated the client ID for the new project, but the issue is not resolved. I am still getting the same error.

Hey @tech7
Can you please share a screenshot of the verifier that you’ve configured for Auth0 login?
It should look like this:

Hey @tech7
Marking this as closed since we solved it in Office Hours.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.