ionic 6 google account firebase

262 views Asked by At

I am using ionic 6. when using the function loginwithgoogle using firebase , it's work perfectly without any error in te web. it's take me to the right page "principal", but the task is setting the app in an Android mobile. after putting the google account informations and click for login, it's take me to other page localhost/login not found.

async loginWithGoogle() {
  try {
    const provider = new GoogleAuthProvider();
    const auth = getAuth();
    signInWithPopup(auth, provider).then(async (result: any) => {
      //console.log(result)
      const credential =
        GoogleAuthProvider.credentialFromResult(result);
      //console.log(credential)
      const googleCredentials = {
        id_token: result.user.accessToken,
        email: result.user.email,
        name: result.user.displayName
      };
      //console.log(googleCredentials)
      const body = JSON.stringify({
        google_credentials: googleCredentials
      });
      const parsedBody = JSON.parse(body);
      const idToken = parsedBody.google_credentials.id_token;
      const headers = new HttpHeaders({
        'Authorization': idToken
      });
      const response: any = await this.http.post(`${this.apiUrl}/login`,
        body, {
          headers
        }).toPromise();
      this.token.setToken(response.token);
      await this.storage.set('auth-token', response.token);
      this.router.navigate(['/principal']);
    })
    //await this.afAuth.signInWithRedirect(new  firebase.auth.GoogleAuthProvider());
  } catch (error) {
    console.error('Error logging in with Google:', error);
  }
}
1

There are 1 answers

1
RGe On

On Android, you have to use the Firebase Android SDK. There are already Capacitor plugins for this.

Example:

import { FirebaseAuthentication } from '@capacitor-firebase/authentication';
import {
  getAuth,
  GoogleAuthProvider,
  signInWithCredential,
} from 'firebase/auth';

const signInWithGoogle = async () => {
  // 1. Create credentials on the native layer
  const result = await FirebaseAuthentication.signInWithGoogle();
  // 2. Sign in on the web layer using the id token
  const credential = GoogleAuthProvider.credential(result.credential?.idToken);
  const auth = getAuth();
  await signInWithCredential(auth, credential);
};

Source

Disclosure: I am the maintainer of @capacitor-firebase/authentication.