如何使用Google Sign In展示认证获取用户电子邮件?

8

目前我正在使用这段代码登录到Google,但是我无法获取用户的电子邮件地址...有人知道如何做到这一点吗?

var LoginGoogle = () => {

  const [request, response, promptAsync] = Google.useAuthRequest({

    androidClientId: 'xxxxxxx.apps.googleusercontent.com',

    expoClientId: 'xxxxxxx.apps.googleusercontent.com'

  },{

    scopes: ["email"]

  },{});

  

  React.useEffect(() => {

    if (response?.type === 'success') {

      const { authentication } = response;

      console.log(response);

      }

  }, [response]);

  return (

    <GoogleSocialButton disabled={!request} onPress={() => {promptAsync()}} />

  ) 

}

响应返回带有链接的对象,而不是电子邮件

2个回答

8

我希望这个内容可以写在Expo文档中。我想从第一个答案中添加一些要点:

  1. 首先,如果您需要代码片段来获取访问令牌后的用户数据,您可以参考此github问题: https://github.com/expo/expo/issues/8384

在接收响应对象后,可以通过以下代码接收访问令牌:

const { authentication: { accessToken } } = response;

然后,您可以创建这样的函数:

async function fetchUserInfo(token) {
  const response = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
  });

  return await response.json();
}

通过在异步函数内使用类似以下方式获取用户对象(其中包含用户电子邮件、个人资料、照片等):

const user = await fetchUserInfo(accessToken);
  1. 但是对于用户对象,请注意使用 https://www.googleapis.com/oauth2/v2/userinfohttps://www.googleapis.com/oauth2/v3/userinfo 将得到略微不同的结果/对象;特别是对于v3,由于Google实现了OpenID Connect API,因此不再有"id"属性,"id"将被称为"sub"。

参考资料:

v3中用户对象的示例:

Object {
  "email": "xxxxx@gmail.com",
  "email_verified": true,
  "family_name": "John Deer",
  "given_name": "John",
  "hd": "gmail.com",
  "locale": "en",
  "name": "John Deer",
  "picture": "https://lh3.googleusercontent.com/a/asdfjasdklfjaslkf",
  "sub": "10998837733652322",
}

希望这能帮助未来的某个人...!

编辑:如果您需要id_token,请查看此链接: expo-auth-session/providers/google Google.useAuthRequest


2
好的回答。感谢您提供链接来源! - Jason

6

1
非常感谢Expo团队提供给我们的API,使得在React Native中进行认证变得更加容易。但是,如果他们能够提示我们需要访问每个提供程序的文档页面以继续操作,那就太好了。或者是我错过了这一点,不管怎样,感谢您的答复! - Jarrett
请问您从哪份文档中获取了这个链接? - Jarrett

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接