在访问令牌受众中找不到OAuth2客户端ID

时间:2020-11-05 16:24:21

标签: firebase react-native oauth-2.0 firebase-authentication google-signin

首先,对不起我的英语不好。 我使用Expo创建了一个Android应用。 我通过Firebase实现了Google登录。 它没有问题。 为了将结果交付给客户,Firebase项目的所有权已移交给客户。 我将权限更改为编辑。

但是有一个问题。

firebase.auth()。signInWithCredential函数导致错误。 错误代码和消息如下。

找不到访问令牌受众中的auth / invalid-credential OAuth2客户端ID。

我已经搜索了错误消息来解决此问题,但是我无法找到它。 这就是为什么我要写Stack Overflow的原因。

LoginScreen.js

import React, { useEffect, useState } from 'react';
import { Button, Image, ImageBackground, Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import * as Google from 'expo-google-app-auth';
import firebase from 'firebase'
import { fireAuth, fireStore } from '../Components/FireConfig';
import { screenHeight, screenWidth } from '../Components/Base';
import i18n from 'i18n-js';
import { ActivityIndicator } from 'react-native-paper';
export function LoginScreen({ navigation, route }) {

    const [isLoading, setIsLoading] = useState(false)

    // var provider = new firebase.auth.GoogleAuthProvider();

    function isUserEqual(googleUser, firebaseUser) {
        if (firebaseUser) {
            var providerData = firebaseUser.providerData;
            for (var i = 0; i < providerData.length; i++) {
                console.log('providerData[i].providerId', providerData[i].providerId)
                console.log('providerData[i].uid', providerData[i].uid)
                if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
                    // providerData[i].uid === googleUser.getBasicProfile().getId()) {
                    providerData[i].uid === googleUser.user.id) {
                    // We don't need to reauth the Firebase connection.
                    return true;
                }
            }
        }
        return false;
    }

    function onSignIn(googleUser) {
        // console.log('Google Auth Response', googleUser);
        // We need to register an Observer on Firebase Auth to make sure auth is initialized.
        var unsubscribe = fireAuth.onAuthStateChanged(function (firebaseUser) {
            unsubscribe();
            // Check if we are already signed-in Firebase with the correct user.
            if (!isUserEqual(googleUser, firebaseUser)) {
                // Build Firebase credential with the Google ID token.
                var credential = firebase.auth.GoogleAuthProvider.credential(
                    //googleUser.getAuthResponse().id_token
                    googleUser.idToken,
                    googleUser.accessToken,
                )
                console.log("credential", credential)
                // Sign in with credential from the Google user.
                fireAuth
                    .signInWithCredential(credential)
                    .then((result) => {
                        const uid = result.user.uid
                        if (result.additionalUserInfo.isNewUser) {
                            fireStore
                                .collection('users')
                                .doc(uid)
                                .set({
                                    google_email: result.user.email,
                                    google_profile_picture: result.additionalUserInfo.profile.picture,
                                    google_locale: result.additionalUserInfo.profile.locale,
                                    google_name: result.additionalUserInfo.profile.name,
                                    created_at: Date.now(),
                                    isPushInfo: false
                                })
                        } else {
                            fireStore
                                .collection('users')
                                .doc(uid)
                                .update({
                                    last_logged_in: Date.now()
                                })
                        }
                    })
                    .catch((e) => {
                        console.log(e.code, e.message)
                    });
            } else {
                console.log('User already signed-in Firebase.', fireAuth.languageCode);
            }
        });
    }

    async function signInWithGoogleAsync() {
        setTimeout(() => {
            setIsLoading(true)
        }, 500)
        try {
            const result = await Google.logInAsync({
                androidClientId : "!!!.apps.googleusercontent.com",
                androidStandaloneAppClientId : "@@@.apps.googleusercontent.com",
                iosClientId : "###.apps.googleusercontent.com",
                iosStandaloneAppClientId : "$$$.apps.googleusercontent.com",
                scopes: ['profile', 'email']
            });
            if (result.type === 'success') {
                console.log(result.type)
                onSignIn(result)
                return result.accessToken;
            } else {
                setIsLoading(false)
                console.log(result)
                alert(result)
                return { cancelled: true };
            }
        } catch (e) {
            setIsLoading(false)
            console.log(e)
            alert(e)
            return { error: true };
        }
    }

    return (
        <View style={styles.container}>
                <TouchableOpacity
                    style={{
                        alignItems: "center",
                        justifyContent: "center",
                        borderRadius: 10,
                        backgroundColor: "white",
                        width: screenWidth * 0.8,
                        height: 50
                    }}
                    title="Sign In With Google"
                    onPress={() => {
                        signInWithGoogleAsync();
                    }} >
                    <Text style={{ color: "#5887f9" }}>{i18n.t('SignInWithGoogle')}</Text>
                </TouchableOpacity>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    }
})

从下面的链接中可以看到

https://console.developers.google.com/apis/credentials

app.json

{
  "expo": 

    ...

    "android": {
      "package": "com.mycompany.myapp",
      "versionCode" : 2,
      "permissions": [
        "READ_EXTERNAL_STORAGE",
        "READ_INTERNAL_STORAGE",
        "WRITE_EXTERNAL_STORAGE",
        "ACCESS_FINE_LOCATION",
        "INTERNET",
        "CAMERA_ROLL",
        "CAMERA"
      ],
      "googleServicesFile": "./google-services.json",
      "useNextNotificationsApi": true,
      "config": {
        "googleMobileAdsAppId": "```",
        "googleSignIn" :{
          "apiKey" : "my apiKey",
          "certificateHash" : "11:22:---:11:22"
        }
      }
    }

    ...

  }
}

API密钥和OAuth 2.0客户端ID必须写为链接中的内容。

我期待着您的合作。

1 个答案:

答案 0 :(得分:4)

关于GitHub上的该票证:https://github.com/FirebaseExtended/flutterfire/issues/4053的Google登录和Firebase身份验证存在中心问题。我联系了GCP支持人员,并在几个小时后将其修复❤️