【问题标题】:firebase facebook failed authenticationfirebase facebook 身份验证失败
【发布时间】:2018-12-05 18:17:47
【问题描述】:

我有一个屏幕,我正在尝试使用 firebase 的 facebook 身份验证。

使用 expo 我可以成功生成 facebook 令牌。接下来我所做的是使用此令牌生成证书,我认为它也成功运行,但是当我尝试使用证书登录到 Firebase 时,我得到错误登录失败。 我不确定是什么问题。在让他们使用 facebook auth 登录之前,我是否需要使用电子邮件和密码注册用户。

任何帮助将不胜感激...

这里是代码...

import React from 'react';
import {
  ActivityIndicator,
  AsyncStorage,
  Button,
  StatusBar,
  StyleSheet,
  View,
  Text,
} from 'react-native';

import Expo, { Facebook } from 'expo';
import * as firebase from 'firebase';

import ModalActivityIndicator from '../../components/ModalActivityIndicator';
export default class SignInFacebookScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
    };
  }
  componentDidMount = async () => {
    await this.facebookLogin();
  };
  facebookLogin = async () => {
    const { type, token } = await Expo.Facebook.logInWithReadPermissionsAsync(
      '<AppId>',
      {
        permissions: ['public_profile', 'email'],
      }
    );

    if (type === 'success') {
      await this.callGraph(token);
    } else if (type === 'cancel') {
      alert('Cancelled!', 'Login was cancelled!');
    } else {
      alert('Oops!', 'Login failed!');
    }
  };
  callGraph = async token => {
    const response = await fetch(
      `https://graph.facebook.com/me?access_token=${token}`
    );
    const userProfile = JSON.stringify(await response.json());
    const credential = firebase.auth.FacebookAuthProvider.credential(token);
    await this.firebaseLogin(credential);
  };
  // Sign in with credential from the Facebook user.
  firebaseLogin = async credential => {
    firebase
      .auth()
      .signInAndRetrieveDataWithCredential(credential)
      .then(() => {
        this.setState({
          isLoading: false,
          hasError: false,
          errorMessage: null,
        });
        this.props.navigation.navigate('App');
      })
      .catch(error => {
        this.setState({
          isLoading: false,
          hasError: true,
          errorMessage: error.errorMessage,
        });
      });
  };

  render() {
    let { isLoading, hasError, errorMessage } = this.state;
    return (
      <View style={styles.container}>
        <ModalActivityIndicator isLoading={!!isLoading} />
        <Text>Sign In with Facebook</Text>
        {hasError && (
          <React.Fragment>
            <Text style={[styles.errorMessage, { color: 'black' }]}>
              Error logging in. Please try again.
            </Text>
            <Text style={[styles.errorMessage, { color: 'black' }]}>
              {errorMessage}
            </Text>
          </React.Fragment>
        )}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

【问题讨论】:

    标签: facebook firebase react-native expo


    【解决方案1】:

    我用下面的代码解决了这个问题。似乎问题在于异步函数的转换。

    import React from 'react';
    import {
      ActivityIndicator,
      AsyncStorage,
      Button,
      StatusBar,
      StyleSheet,
      View,
      Text,
    } from 'react-native';
    
    import Expo, { Facebook } from 'expo';
    import * as firebase from 'firebase';
    
    import ModalActivityIndicator from '../../components/ModalActivityIndicator';
    
    export default class SignInFacebookScreen extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          isLoading: false,
          firstName: '',
          lastName: '',
        };
      }
      componentDidMount = async () => {
        const fbToken = await this.getFacebookToken();
        const userProfile = await this.getFacebookUserProfile(fbToken);
        this.setUserDetails(userProfile);
        const credential = await this.getFirebaseFacebookCredential(fbToken);
        await this.loginToFirebaseWithFacebook(credential);
      };
    
      getFacebookToken = async () => {
        const { type, token } = await Expo.Facebook.logInWithReadPermissionsAsync(
          '<AppId>',
          {
            permissions: ['public_profile', 'email'],
          }
        );
        if (type === 'success') {
          return token;
        } else if (type === 'cancel') {
          alert('Cancelled!', 'Login was cancelled!');
        } else {
          alert('Oops!', 'Login failed!');
        }
      };
    
      getFacebookUserProfile = async token => {
        this.setState({ isLoading: true });
        const response = await fetch(
          `https://graph.facebook.com/me?access_token=${token}&fields=first_name,last_name`
        );
        const userProfile = JSON.stringify(await response.json());
        return userProfile;
      };
    
      setUserDetails = userProfile => {
        const userProfileObj = JSON.parse(userProfile);
        this.setState({
          firstName: userProfileObj.first_name,
          lastName: userProfileObj.last_name,
        });
      };
    
      getFirebaseFacebookCredential = async token => {
        const credential = firebase.auth.FacebookAuthProvider.credential(token);
        return credential;
      };
    
      loginToFirebaseWithFacebook = async credential => {
        firebase
          .auth()
          .signInAndRetrieveDataWithCredential(credential)
          .then(() => {
            let user = firebase.auth().currentUser;
            firebase
              .database()
              .ref('users/' + user.uid)
              .update({
                firstName: this.state.firstName,
                lastName: this.state.lastName,
              });
          })
          .then(() => {
            this.setState({
              isLoading: false,
              haserror: false,
              errorMessage: null,
            });
            this.props.navigation.navigate('App');
          });
      };
    
      render() {
        let { isLoading, hasError, errorMessage } = this.state;
        return (
          <View style={styles.container}>
            <ModalActivityIndicator isLoading={!!isLoading} />
            <Text>Sign In with Facebook</Text>
            {hasError && (
              <React.Fragment>
                <Text style={[styles.errorMessage, { color: 'black' }]}>
                  Error logging in. Please try again.
                </Text>
                <Text style={[styles.errorMessage, { color: 'black' }]}>
                  {errorMessage}
                </Text>
              </React.Fragment>
            )}
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
      },
    });
    

    【讨论】:

      猜你喜欢
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 2017-08-24
      • 2018-12-06
      • 1970-01-01
      相关资源
      最近更新 更多