我用Firebase和React.js创建了一个web应用程序,并实现了与谷歌的登录。然后我尝试实现GoogleOneTapSignin和一键登录UI工作成功,因为我使用了react-google-一键登录npm包。如果可能反应app我有一个功能,监听AuthStateChange,然后要么注册用户,如果他们是新的或登录他们,如果他们已经是一个成员,也更新状态,如果他们登录。出去了。现在我已经实现了google-one-tap-login,我期待onAuthSTaetChanged函数被触发,如果用户使用google-one-tap-login登录,但事实并非如此。下面是我的App.js代码中处理用户授权的部分。
const classes = useStyles();
const dispatch = useDispatch();
const alert = useSelector(state => state.notification.alert);
// Handling Google-one-tap-signin
useGoogleOneTapLogin({
onError: error => console.log(error),
onSuccess: response => {
console.log(response);
const credential = provider.credential(response);
auth.signInWithCredential(credential).then(result => {
const {
user
} = result;
console.log(user);
});
},
googleAccountConfigs: {
client_id: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}
});
//Handling firebase authentification
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(async user => {
// If there is a user create the user profile and update useState
if (user) {
// createUserProfile function creates the user profile in firestore if they are new
const userRef = await createUserProfileDocument(user);
userRef.onSnapshot(snapshot => {
const doc = snapshot.data();
dispatch(
setUser({
id: snapshot.id,
...doc
})
);
});
} else {
dispatch(setUser(null));
}
});
return () => {
unsubscribe();
};
}, [dispatch]);
我试图实现这个StackOverflow问题的第二个答案所建议的解决方案,但我在控制台上得到下面的错误。当我使用谷歌一键登录时。记住,我没有使用FirebaseUi库。到目前为止,我的应用程序只使用登录与谷歌
t {
code: "auth/argument-error",
message: "credential failed: must provide the ID token and/or the access token.",
a: null
}
a: null
code: "auth/argument-error"
message: "credential failed: must provide the ID token and/or the access token."
Firebase的signInWithCredential
函数所需的ID令牌存在于response
对象的credential
属性中。下面是一个使用Firebase V8的示例函数。
// firebase V8
function handleCredentialResponse(response) {
if (response) {
const cred = auth.GoogleAuthProvider.credential(response.credential);
// Sign in with credential from the Google user.
return auth().signInWithCredential(cred);
}
}
重火力点v9
// firebase V9
import { getAuth, GoogleAuthProvider, signInWithCredential } from "firebase/auth";
const auth = getAuth();
function handleCredentialResponse(response) {
if (response) {
const cred = GoogleAuthProvider.credential(response.credential)
// Sign in with credential from the Google user.
return signInWithCredential(auth, cred);
}
}
response
参数是从Google一键函数回调返回的凭据响应。
google?.accounts.id.initialize({
client_id: your-google-app-client-id.apps.googleusercontent.com,
callback: handleCredentialResponse,
});
google?.accounts.id.prompt((notification) => {
console.log(notification);
});