React-native-firebase: How to setup google sign in with react-native-firebase?

Created on 25 Jul 2017  Â·  35Comments  Â·  Source: invertase/react-native-firebase

  1. Target Platform (e.g. iOS, Android): Android
  2. Development Operating System (e.g. macOS Sierra, Windows 10): Windows 10
  3. Build tools (Xcode or Android Studio version, iOS or Android SDK version, if relevant):
  4. React Native version (e.g. 0.45.1): 0.45
  5. RNFirebase Version (e.g. 2.0.2): 1.1.2

Hello, I'm trying to authenticate with firebase auth using react-native-firebase library but seems like there are lots of issues coming in, I have not initialized webClientId or defined it and what I'm doing right now is that I'm currently sending my accessToken like this:

 GoogleSignin.signIn().then((user) => {
            console.log(user);
            this.setState({user: user});
            console.log(user.token+" token");
            const credential = {
                provider: 'google',
                token: user.accessToken,
                secret: user.id, //I do not know what to send in secret
            };            
            Authentication.googleLogin(credential);
        })
            .catch((err) => {
               alert('WRONG SIGNIN'+ err);
            })
            .done();

and here is my authentication firebase code:

static googleLogin(getCredentials) {
        //this.setState({user: user});
        firebase.auth().signInWithCredential(getCredentials)
            .then((user) => {
                console.log('User successfully signed in', user)
            })
            .catch((err) => {
                console.error('User signin error', err);
            });
    }

Upon running, it throws me this error:

> User signin error Error: An internal error has occurred. [ Unable to parse Google id_token: -accessToken-

And then I did some research on how I can fix this and turns out that some articles said that I need idToken which I do not know how to get, I have not initialized my webClientId yet so that is the reason I think I'm currently getting null at, I do not know how to set that up so I tried to edit my config method like this which did not give me any tokenId:

_configureOauth(clientId, scopes=[]) {
        GoogleSignin.configure(
            "myIdhere", 
            [], // I do not know what to put here either
            "https://my-app.firebaseio.com/auth" //I also tried without auth
        );
}

so after all these attempts and seaching up the whole github I was not able to find any solution so this is the last thing but I since there are 74 issues which are open I don't think that this will be solved here so easily but please if you know the solution to this please answer. Thank you!

General Docs Waiting for User Response

Most helpful comment

@pravinraut809 if you want a full code example, consider purchasing our auth starter kit which has everything set up for you: https://rnfirebase.io/kits/auth-starter

All 35 comments

You need to build your credential the following way:

const credential = firebase.auth.GoogleAuthProvider.credential(idToken, accessToken);

So you will need to get idToken from your oauth library of choice

@Salakar I have tried doing it that way but doing so gives me error that the "GoogleAuthProvider" is undefined.

Ah, you'll need to upgrade your RNFirebase to the latest version - migration guide is over here - it's fairly straight forward

@Salakar I have lots of code in iOS that is incompatible in the current but I tried making an empty project and doing it all from scratch but I'm still getting the same error that its undefined, please help :( Do you have any google sign in examples that use this library? and please it would be alot helpful if there is any fix for the version 1.1.2

@ShariqMush try using your initialised instance of firebase to access the auth.GoogleAuthProvider using the module one from import firebase from 'react-native-firebase'; won't work - at least not in v1.1.2.

e.g:

import firebase from 'react-native-firebase';

const instance = firebase.intializeApp({
     // your opts
});

// ...
const credential = instance.auth.GoogleAuthProvider.credential(idToken, accessToken);

@Salakar Yes I tried, but right now after trying to migrate to v2, I'm getting some dex error

com.android.dex.DexException: Multiple dex files define in android app

Please see the faqs on how to fix that problem :)

On 31 Jul 2017 09:06, "Shariq Musharaf" notifications@github.com wrote:

@Salakar https://github.com/salakar Yes I tried, but right now after
trying to migrate to v2, I'm getting some dex error

com.android.dex.DexException: Multiple dex files define in android app

—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/invertase/react-native-firebase/issues/275#issuecomment-318997610,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAzZXl3u6rGBHXxaNGkvT9yGfislJptlks5sTYrvgaJpZM4OieR2
.

@Ehesp I have tried all the info that was in the FAQ and also from the link that was provided there but nothing seems to work for me right now :(
This is my current app gradle file(dependencies):

dependencies {
    compile ('com.google.gms:google-services:+')
            {
                exclude group: "com.google.android.gms" // very important
            }
    compile project(':react-native-config')
    compile project(':react-native-video')
    compile project(':lottie-react-native')
    compile project(':react-native-svg')
    compile project(':react-native-photo-view')
    compile project(':react-native-share')
    compile project(':react-native-linear-gradient')
    compile project(':react-native-material-kit')
    compile project(':react-native-vector-icons')
    compile project(':react-native-sqlite-storage')
    compile "com.facebook.android:facebook-android-sdk:4.22.1)"
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(":react-native-i18n")
    compile(project(":react-native-google-signin")){
        exclude group: "com.google.android.gms" // very important
    }
    compile ('com.google.android.gms:play-services-auth:10.2.6'){
        force = true;
    }
    compile ("com.google.android.gms:play-services-base:+") { // the plus allows you to use the latest version
        force = true;
    }

    compile (project(path: ':react-native-fbsdk'))
            {
                exclude group: "com.google.android.gms"
            }
    compile(project(":react-native-firebase")){
        exclude group: "com.google.android.gms"
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply plugin: 'com.google.gms.google-services'

I'd guess other dependancies still have dependancies towards Google Services. You need to go through them one by one, annoying issue but requires manual work which we can't really help with since it's project specific.

@Ehesp I have checked through all of the dependencies, the place where I found com.google.android.gms was only in react-native-firebase and react-native-google-signin. Do I have to exclude this in the other dependencies gradles files?

It's not just the Google ones, any dependancy conflict will throw the error.

@Ehesp Currently it is giving me this error

Execution failed for task ':app:processDebugGoogleServices'.
Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gm
s.google-services/) or updating the version of com.google.android.gms to 10.2.6

But I don't know how to update this, I took the code from the website provided here and put it in my dependencies but its still throwing the error. I'm now going to do as you said and will reply after trying as you said.

@ShariqMush you should be asking for the same versions of the com.google.android.gms:play-services-auth, com.google.android.gms:play-services-base and com.google.gms:google-services rather than specifying a version for one and open ended for another. Try setting them all to 10.2.6 or the latest version which I think is 11.0.2

@chrisbianca Thanks for that! :) and now I'm back to

com.android.dex.DexException: Multiple dex files define Lcom
/google/android/gms/common/api/zzf;

If you run ./gradlew app:dependencies in your android directory, you'll get a rather unwieldy list of dependencies that are being used by the app. If you go through that, you should be able to see which libraries are requesting gms dependencies and exclude them.

@chrisbianca Thanks soo much!!! I can only see com.google.firebase:firebase-core:11.0.0 in react-native-firebase and com.google.android.gms:play-services-auth:10.2.6 in google signin requiring gms dependencies, I'm going to try to exclude them now.

@ShariqMush Has this worked for you? If so, can we close the issue?

@chrisbianca No, I'm still trying to sort the dex issue out, now I'm making an empty project and adding all the dependencies one by one and doing setup from the scratch to find out what is causing the conflict... It would be very greatful of you if you could try to reproduce the problem in an empty project in your side :)

@ShariqMush As much as we'd like to, you'll have to work through this on your own - we know what the issue is and have provided steps to fix it. Unfortunately every project uses its own combination of modules and we don't have the resource to be able to go to such a level of detail with each specific configuration.

@chrisbianca @Ehesp @Salakar I have now tried to install rn-firebase in an empty project and now I'm getting all these errors when I try to do react-native run-android
Errors:

path\RNFirebaseAdMobPackage.java:39: error: method does not override or implement a method from a supertype
  @Override
  ^
path\RNFirebaseAnalyticsPackage.java:38: error: method does not override or implement a method from a supertype
  @Override
  ^
path\RNFirebaseAuthPackage.java:38: error: method does not override or implement a method from a supertype
  @Override
  ^
path\RNFirebaseRemoteConfigPackage.java:38: error: method does not override or implement a method from a supertype
  @Override
  ^
path\RNFirebaseCrashPackage.java:38: error: method does not override or implement a method from a supertype
  @Override
  ^
path\RNFirebaseDatabasePackage.java:38: error: method does not override or implement a method from a supertype
  @Override
  ^
path\RNFirebaseMessagingPackage.java:38: error: method does not override or implement a method from a supertype
  @Override
  ^
path\RNFirebasePerformancePackage.java:38: error: method does not override or implement a method from a supertype
  @Override
  ^
path\RNFirebasePackage.java:41: error: method does not override or implement a method from a supertype
  @Override
  ^
path\RNFirebaseStoragePackage.java:38: error: method does not override or implement a method from a supertype
  @Override
  ^
path\RNFirebaseAuth.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
10 errors
:react-native-firebase:compileReleaseJavaWithJavac FAILED

You need to bump the version of RNFirebase to 2.1.0.
React Native 0.47.0 had some breaking changes for Android

@chrisbianca @Ehesp @Salakar To debug, I installed both google-signin and rn-firebase packages in an empty project but now the app crashes on the launch and throws this error in the android logcat:
FATAL EXCEPTION: main

Process: com.firebasetest, PID: 15629 java.lang.NoSuchMethodError: No static method zzb(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; in class Lcom/google/android/gms/common/internal/zzbr; or its super classes (declaration of 'com.google.android.gms.common.internal.zzbr' appears in /data/app/com.firebasetest-2/base.apk) at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source) at android.app.ActivityThread.installProvider(ActivityThread.java:5153) at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688) at android.app.ActivityThread.-wrap1(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

@chrisbianca @Salakar @Ehesp I skipped to update the rn-firebase and continued with 1.1.2 and then I implemented the google signin correctly and used the loginwithcredentials to log in this time and now I can successfully log in. But I can't save the email for some reason, when I try to get the user email, it gives me null or undefined. Here is the code:

GoogleSignin.signIn().then((user) => {
            console.log(user);
            this.setState({user: user});
            console.log(user.token + " token");
            let credential = {
                provider: 'google',
                token: user.idToken,
                secret: user.serverAuthCode,
                provider: 'google',
                email: user.email,
                providerId: 'google'
            };
            console.log(credential);
            Authentication.googleLogin(credential);
        })
            .catch((err) => {
                alert('WRONG SIGNIN' + err);
            })
            .done();
static googleLogin(getCredentials) {
        //this.setState({user: user});
        firebase.auth().signInWithCredential(getCredentials)
            .then((user) => {
                console.log('User successfully signed in', user)
                var user = firebase.auth().currentUser;
                console.log("Email: "+user.email);
            })
            .catch((err) => {
                console.error('User signin error', err);
            });
    }

Here is the issue where I got this help from: https://github.com/devfd/react-native-google-signin/issues/263
And I can see the user email in the firebase except not here when I try to get it from the .CurrentUser()

@ShariqMush you'll need to get it from provider data, see https://firebase.google.com/docs/auth/web/manage-users#get_a_users_provider-specific_profile_information

Hi.
We've managed to get https://github.com/devfd/react-native-google-signin working with this library using this code (I've reduced it):
https://gist.github.com/erezrokah/be11192a4faf01ded0f7f17a549cb07e

I'm assuming you have both libraries setup correctly.
I can share our gradle file if that is required.

@Salakar @Ehesp @chrisbianca Thank you for your help guys!! I have managed to make it work with signInWithcredential!! Thank you so much, you are the best!

@ShariqMush To clarify, you needed react-native-firebase and react-native-google-signin to get google auth working with signInWithCredential?

Yes, RNFirebase doesn't do anything to get you a token, it just provides a means to sign in with a token from elsewhere.

Just a question, can i use firebase package instead of react-native-firebase for google authentication like this?

Or i still need to use this library?

You need Google sign in before Firebase

Here is a snippet that signs you in, since I saw some examples using only idToken which can be null and you can use accessToken too

GoogleSignin.configure({}).then(() => {
      GoogleSignin.hasPlayServices({ autoResolve: true })
        .then(() => {
          GoogleSignin.signIn()
            .then(user => {
              console.log(user);

              const credential = firebase.auth.GoogleAuthProvider.credential(
                user.idToken,
                user.accessToken
              );

              firebase
                .auth()
                .signInWithCredential(credential)
                .then(user => {
                  console.log("user firebase ", user);
                  if (user._authObj.authenticated) {
                    // do you login action here
                    // dispatch({
                    //  type: LOGIN_SUCCESS,
                    //  payload: { ...user._user, loggedIn: true }
                    //});
                  }
                });
            })
            .catch(err => {
              console.log("WRONG SIGNIN", err);
            })
            .done();
        })
        .catch(err => {
          console.log("Play services error", err.code, err.message);
        });
   });

Plss ,, Someone get me the full code.....

@pravinraut809 it's basically above you.

Sir,, want the full code ..

Also for phone auth

@pravinraut809 if you want a full code example, consider purchasing our auth starter kit which has everything set up for you: https://rnfirebase.io/kits/auth-starter

Was this page helpful?
0 / 5 - 0 ratings