如何从 Expo GoogleSignIn API (expo v32) 获取 idToken?

Posted

技术标签:

【中文标题】如何从 Expo GoogleSignIn API (expo v32) 获取 idToken?【英文标题】:How to get idToken from Expo GoogleSignIn API (expo v32)? 【发布时间】:2019-08-29 01:45:49 【问题描述】:

我正在尝试使用 Expo GoogleSignIn API 在 react-native 上设置原生 Google 身份验证,但无法获取授权 Google 用户的 idToken。

它有 accessToken 作为响应,但没有 idToken。

所以我使用了一些简单的代码,例如

const result = await GoogleSignIn.initAsync(
                isOfflineEnabled: true,
                isPromptEnabled: true,
                //webClientId: 'webClientId',
                clientId // now testing only on android, so this is irrelevant
                );
console.log(result);

示例响应:

 Object 
    "auth": Object 
      "accessToken": "accessToken",
      "accessTokenExpirationDate": null,
      "idToken": null,  // here is the problem!
      "refreshToken": null,
    ,
    "displayName": "Danila Tsvetkov",
    "email": "email@email",
    "firstName": "Danila",
    "hostedDomain": undefined,
    "lastName": "Tsvetkov",
    "serverAuthCode": null,
    "uid": "uid",
  

同时GoogleOAuth API不仅返回accessToken,还返回idToken和refreshToken。

其他一切正常,例如授权和登录流程。

也许问题出在 serverAuthCode 上?

试图把webClientId,api停止正常工作。将 SHA1 添加到 google-services (more info),没有帮助。更改诸如“isOfflineEnabled”之类的其他参数也无济于事。

【问题讨论】:

【参考方案1】:

你能用这个吗

const result = await Google.logInAsync(
          androidClientId: "android id"
          iosClientId: 'Ios Id',
          scopes: ['profile', 'email'],
        );

然后

 if (result.type === 'success') 
          console.log(result.idToken);
//or
          Alert.alert(result.idToken);
        

【讨论】:

【参考方案2】:

if (result.type === 'success') 
     console.log(result.user.auth);

这是因为我们使用的是 google-sign-in,而不是 expo-google-app-auth

总之,使用 result.user.auth,但在此之前,您的代码应该是这样的

signInAsync = async () => 
    try 
      await GoogleSignIn.askForPlayServicesAsync();
      const result = await GoogleSignIn.signInAsync();
      if (result.type === 'success') 
        
        this.onSignIn(result.user.auth);
        return result.user.auth;
      
     catch ( message ) 
      alert('login: Error:' + message);
    
  ;

【讨论】:

以上是关于如何从 Expo GoogleSignIn API (expo v32) 获取 idToken?的主要内容,如果未能解决你的问题,请参考以下文章

GoogleSignIn 重复登录弹出窗口并且不会转到 Android API 30 的 onActivityResult

将 Android GoogleSignIn 与 GmailScopes.GMAIL_SEND 一起使用(gmail api)

Expo iOS Build 无法正常工作--“无法从 App Store Connect 接收最新的 API 密钥”

Expo大作战(三十二)--expo sdk api之Noifications

Expo大作战(二十六)--expo sdk api之Video和WebBrowser

Expo大作战(二十七)--expo sdk api之Util(expo自带工具类),tackSnapshotAsync,Svg,SQLite