使用 React Native 获取 OAuth 的 Google 和 Facebook 访问令牌的最佳方法是什么?

What is the best way to get Google and Facebook access token for OAuth using React Native?

我正在服务器端获取配置文件。只想要我前端的访问令牌。

passport.use('google', new GooglePlusTokenStratey ({

clientID: process.env.GCID,
clientSecret: process.env.GCS,


}, async(accessToken, refreshToken, profile, done) => {
console.log("accessToken ",accessToken);
console.log("refreshToken ",refreshToken);
console.log("profile ",profile);

const existingUser = await Social.findOne({ "uid": profile.id });
if (existingUser) {
  return done(null, existingUser);
}

const newUser = new Social({
    method: "google",
    email: profile.emails[0].value,
    name: profile.displayName,
    uid: profile.id  
  });

  await newUser.save();
  done(null, newUser);

}));

我现在使用 postman 调用路由并在 JSON 中发送访问令牌,但想使用 react-native 实现它。

Google 登录

使用@react-native-community/google-signin.

常见用例:

import { GoogleSignin, statusCodes } from '@react-native-community/google-signin';

// Somewhere in your code
const googleLogin = async () => {
    try {
      await GoogleSignin.hasPlayServices();
      const googleUser = await GoogleSignin.signIn();
      const accessToken = googleUser.idToken;
    } catch (e) {
      if (e.code === statusCodes.SIGN_IN_CANCELLED) {
        console.log('User cancelled google login');
      } else if (e.code === statusCodes.IN_PROGRESS) {
        console.log('Sign in in progress');
      } else if (e.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        console.log('Play service not available');
      } else {
        console.log('Unknown google sign in error');
      }
    }
  };

Facebook 登录

使用react-native-fbsdk

常见用例:

import React, { Component } from 'react';
import { View } from 'react-native';
import { LoginButton, AccessToken } from 'react-native-fbsdk';

export default class Login extends Component {
  render() {
    return (
      <View>
        <LoginButton
          onLoginFinished={
            (error, result) => {
              if (error) {
                console.log("login has error: " + result.error);
              } else if (result.isCancelled) {
                console.log("login is cancelled.");
              } else {
                AccessToken.getCurrentAccessToken().then(
                  (data) => {
                    console.log(data.accessToken.toString())
                  }
                )
              }
            }
          }
          onLogoutFinished={() => console.log("logout.")}/>
      </View>
    );
  }
};

以上回答正确。但是,如果您使用的是 expo,那么您可能必须手动 link 软件包。世博会用户更好的解决方案:

对于Google登录

使用:https://docs.expo.io/versions/latest/sdk/google/

'''

import * as Google from 'expo-google-app-auth';

const { type, accessToken, user } = await Google.logInAsync({
  iosClientId: `<YOUR_IOS_CLIENT_ID_FOR_EXPO>`,
  androidClientId: `<YOUR_ANDROID_CLIENT_ID_FOR_EXPO>`,
  iosStandaloneAppClientId: `<YOUR_IOS_CLIENT_ID>`,
  androidStandaloneAppClientId: `<YOUR_ANDROID_CLIENT_ID>`,
});

if (type === 'success') {
  /* `accessToken` is now valid and can be used to get data from the Google API with HTTP requests */
  console.log(user);
}

'''

对于 Facebook 登录

使用:https://docs.expo.io/versions/latest/sdk/facebook/

'''

async function logIn() {
  try {
    await Facebook.initializeAsync('<APP_ID>');
    const {
      type,
      token,
      expires,
      permissions,
      declinedPermissions,
    } = await Facebook.logInWithReadPermissionsAsync({
      permissions: ['public_profile'],
    });
    if (type === 'success') {
      // Get the user's name using Facebook's Graph API
      const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`);
      Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);
    } else {
      // type === 'cancel'
    }
  } catch ({ message }) {
    alert(`Facebook Login Error: ${message}`);
  }
}

'''