Home > Enterprise >  How does firebase authentication work with ionic and capacitor?
How does firebase authentication work with ionic and capacitor?

Time:12-24

When the app is launching for the sign in page, an error is occurring that relates to the authorized domains: Cross-origin redirection to http://developers.google.com/ denied by Cross-Origin Resource Sharing policy: Origin capacitor://localhost is not allowed by Access-Control-Allow-Origin. Status code: 301

When I try to add capacitor://localhost to the list of authorized domains, it throws the error A valid domain name is required (e.g. 'myapp.com')

My authentication code both has a listener:

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (userInfo) => {
      setUser(userInfo);
      if (userInfo === null) {
        localStorage.clear();
        history.push("/login");
      } else {
        const token = await userInfo.getIdToken(true);
        history.push("/home");
        localStorage.setItem("AuthToken", `Bearer ${token}`);
      }
    });
    return unsubscribe;
  }, [user, history]);

and the sign in function:


export const signIn = async (email, password) => {
  try {
    await setPersistence(auth, browserLocalPersistence);
    const userCredential = await signInWithEmailAndPassword(
      auth,
      email,
      password
    );

    const user = userCredential.user;
    const token = await user.getIdToken(true);
    localStorage.setItem("AuthToken", `Bearer ${token}`);
    return { user, token };
  } catch (error) {
    return { error: error.message };
  }
};

I have seen some answers that might suggest it has to do with the Firebase Auth SDK having issues with capacitor because it is meant for a web app instead of mobile apps. However, there has not been very clear answers as to how I can confirm if that is the problem or how to solve it.

CodePudding user response:

The solution was to implement this when using the firebase auth object

function whichAuth() {
  let auth;
  if (Capacitor.isNativePlatform()) {
    auth = initializeAuth(app, {
      persistence: indexedDBLocalPersistence,
    });
  } else {
    auth = getAuth(app);
  }
  return auth;
}

export const auth = whichAuth();

CodePudding user response:

It looks like you are trying to redirect to the Google Developer website from an app that is running on capacitor://localhost. This error is occurring because the browser is blocking the redirect due to a security feature called the "same-origin policy".

  • Related