Firebase idToken中缺少Givenname和Familyname声明

人气:974 发布:2022-10-16 标签: javascript firebase firebase-authentication google-signin

问题描述

我正在尝试使用Firebase为我们的Web应用程序实现Google登录。 下面是我为获取idToken所做的工作:

  const google_provider = new GoogleAuthProvider();
  google_provider.addScope("openid");
  google_provider.addScope("profile");
  google_provider.addScope("email");
  signInWithPopup(auth, google_provider).then((result) =>
    result.user.getIdToken());

虽然我已经添加了配置文件作用域,但我仍然无法获得idtoken中的givennamefamilyname(emailpicturename是可用的)

(我尝试直接使用Google登录,在那里我可以看到所有个人资料声明)

我在这里错过了什么?我做错了什么吗?

推荐答案

getIdToken()返回的Firebase ID令牌不包含您正在查找的用户的谷歌帐户信息(预期名称、个人资料图像等)。您应该使用从登录结果中检索到的访问代码向Google API发出获取它的请求。

signInWithPopup(auth, provider)
  .then(async (result) => {
    // This gives you a Google Access Token. You can use it to access the Google API.
    const credential = GoogleAuthProvider.credentialFromResult(result);
    const token = credential.accessToken;

    const response = await fetch('https://www.googleapis.com/oauth2/v1/userinfo', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })

    const data = await response.json();
    console.log(data);
  })

637