firebasereact-nativeauthenticationgoogle-cloud-functionsgoogle-authentication

react native google sign in - firebase invalid token


Fixed: So the token I receive from react-native-google-signin is not enough, I was also supposed to install firebase and auth with it as seen in the accepted answer, then use the token from firebase.

Original Post:

I am using react-native-google-signin to login user to an app, on sign-in I get a jwt token.

On firebase I have the following https cloud function:

exports.verify = functions.https.onRequest((req, res) => {
  const tokenId = req.get('Authorization').split('Bearer ')[1];
  return admin.auth().verifyIdToken(tokenId)
    .then((decoded) => res.status(200).send(decoded))
    .catch((err) => res.status(401).send(err));
});

When I send the token from react-native-google-signin for verification I get the following response:

{
    "code": "auth/argument-error",
    "message": "Firebase ID token has incorrect \"aud\" (audience) claim. Expected \"my-project\" but got \"1232345345-sdfsdfsdfsdf.apps.googleusercontent.com\". Make sure the ID token comes from the same Firebase project as the service account used to authenticate this SDK. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token."
}

In this case the aud is the webclient ID from firebase google sign in authentication method of 'my-project'. How would I fix this since it's firebase giving me the token and it's firebase rejecting the token ...


Solution

  • First, be sure that the Firebase project being used to host your cloud function is the same Firebase project used in the React app.

    Second, ensure that in the React app, you are retrieving the Firebase user and then calling getIdToken.

    Example

    import { GoogleSignin } from 'react-native-google-signin';
    
    onLoginOrRegister = () => {
      GoogleSignin.signIn()
        .then((data) => {
          const credential = firebase.auth.GoogleAuthProvider.credential(data.idToken, data.accessToken);
          return firebase.auth().signInWithCredential(credential);
        })
        .then((user) => {
    
          // ** Now that the user is signed in, you can get the ID Token. **
    
          user.getIdToken(/* forceRefresh */ true).then(function(idToken) ... 
    
        })
        .catch((error) => {
          const { code, message } = error;
        });
    }
    firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken)