【问题标题】:What is the best way to get Google and Facebook access token for OAuth using React Native?使用 React Native 为 OAuth 获取 Google 和 Facebook 访问令牌的最佳方法是什么?
【发布时间】:2020-11-18 20:43:53
【问题描述】:

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

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);

}));

我现在使用邮递员调用路由并以 JSON 格式发送访问令牌,但想使用 react-native 来实现它。

【问题讨论】:

    标签: node.js reactjs react-native access-token facebook-access-token


    【解决方案1】:

    谷歌登录

    使用@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>
        );
      }
    };
    

    【讨论】:

    • @JunaidAhmed 太好了,您成功了。继续!
    • 谢谢!这工作正常,但对于世博会用户,请参阅下面的答案。
    【解决方案2】:

    以上答案是正确的。但是,如果您使用的是 expo,那么您可能必须手动链接这些包。为博览会用户提供更好的解决方案:

    对于谷歌登录

    使用: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}`);
      }
    }
    

    '''

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-10
      • 2018-02-05
      • 1970-01-01
      • 2011-09-04
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      相关资源
      最近更新 更多