1

文档看来,除了使用将 authCode 作为强制参数的 GoogleCredential 构造函数之外,似乎没有其他方法可以使用 Google 登录,我应该如何获取它?

有关 [[loginWithRedirect]] 的示例,请参阅 Facebook 身份验证

此外,文档中有多个对名为 loginWithRedirect 的函数的引用,但它们不会链接到任何地方,并且在名为 loginWithRedirect 的 auth 对象中没有属性。

4

1 回答 1

4

实际上,RN 和服务器 SDK 不支持重定向概念。您必须获得自己的 authCode。

Stitch 的 GoogleCredential 构造函数只需要一个有效的服务器身份验证代码,以便 Stitch 服务可以使用离线访问

使用第三方 OAuth 模块

我没有运气使用带有 RN 的官方 google-auth-library SDK。我能够使用react-native-community 的 react-native-google-signin使其工作(至少在 iOS 上 - 还没有尝试过 Android)。安装过程有点复杂,所以请务必仔细按照他们的说明进行操作!

我将展示我如何使用这个特定的库来登录。希望这些信息可以应用于其他 OAuth 库和其他身份验证提供程序(例如 Facebook)。

配置谷歌登录

必须指定 webClientId 并且必须与 Stitch UI 上 Google Oauth2 配置下的客户端 ID 匹配(参见屏幕截图)。iosClientId 位于您按照这些步骤下载的 GoogleService-Info.plist 中。最后,将 offlineAccess 设置为 true。

如果您直接使用 Google iOS SDK 或其他库,请注意 webClientId 称为serverClientID而 iosClientId 简称为clientId

这是我的配置代码(请参阅我的完整App.js 文件):

componentDidMount() {
  // ...
  GoogleSignin.configure({
    webClientId: '<id>', // from Stitch UI > Users > Providers > Google
    offlineAccess: true,
    iosClientId: '<id>', // CLIENT_ID in GoogleService-Info.plist
  });
}

呈现 GoogleSigninButton

react-native-google-signin 提供了一个不错的按钮,我渲染出来了(见截图):

const loginButton = <GoogleSigninButton
  style={{ width: 192, height: 48 }}
  size={GoogleSigninButton.Size.Wide}
  color={GoogleSigninButton.Color.Dark}
  onPress={this._onPressLogin}
  disabled={this.state.isSigninInProgress}
/>

给 Stitch 来自 GoogleSignin 的 serverAuthCode

我的 _onPressLogin 函数使用 GoogleSignin 来获取 serverAuthCode。然后它将该代码传递给 Stitch:

_onPressLogin = async () => {
  // They recommend calling this before signIn
  await GoogleSignin.hasPlayServices();

  // Call signIn to get userInfo
  const userInfo = await GoogleSignin.signIn();

  // Check if serverAuthCode was received -- it will be null
  // if something wasn't configured correctly. Be sure to
  // log out after changing a configuration.
  const {serverAuthCode} = userInfo;
  if (serverAuthCode === null) {
    throw new Error('Failed to get serverAuthCode!');
  }
  try {
    // Pass serverAuthCode to Stitch via GoogleCredential
    const user = await this.state.client.auth.loginWithCredential(new GoogleCredential(serverAuthCode));
    console.log(`Successfully logged in as user ${user.id}`);
    this.setState({ currentUserId: user.id });
  } catch(err) {
    console.error(`Failed to log in anonymously: ${err}`);
    this.setState({ currentUserId: undefined })
  }

注销

我发现我必须在测试时多次注销(并确定在哪里使用哪些客户端 ID),否则 serverAuthCode 将返回 null。让注销按钮始终可见是件好事。我的注销代码如下所示:

_onPressLogout = async () => {
  await GoogleSignin.revokeAccess();
  await GoogleSignin.signOut();
  const user = await this.state.client.auth.logout();
  console.log(`Successfully logged out`);
  this.setState({ currentUserId: undefined })
}

我希望这有帮助!

于 2019-03-14T22:50:49.330 回答