使用firebase phone auth验证本机做出反应失败

时间:2018-04-29 10:26:34

标签: android firebase react-native

我试图通过react-native-firebase docs与firebase phone auth做出本地反应 我收到此错误

  

错误:此应用无权使用Firebase身份验证。请确认在Firebase控制台中配置了正确的软件包名称和SHA-1。 [应用验证失败]

我已经创建了debug.keystore

keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -validity 14000

然后我得到了SHA1

keytool -list -alias androiddebugkey -keystore "C:\Users\adirz\.android\debug.keystore" -storepass android -keypass android

并粘贴到firebase控制台并下载google-services.json并添加到我的本机应用程序。 然后进入我写的代码

    import React, { Component } from 'react';
import {
  View,
  Button,
  Text,
  TextInput,
  Image,
  ActivityIndicator,
  Platform,
} from 'react-native';

import firebase from 'react-native-firebase'

const imageUrl =
  'https://www.shareicon.net/data/512x512/2016/07/19/798524_sms_512x512.png';

export default class PhoneAuth extends Component {
  static getDefaultState() {
    return {
      error: '',
      codeInput: '',
      phoneNumber: '+44',
      auto: Platform.OS === 'android',
      autoVerifyCountDown: 0,
      sent: false,
      started: false,
      user: null,
    };
  }

  constructor(props) {
    super(props);
    this.timeout = 20;
    this._autoVerifyInterval = null;
    this.state = PhoneAuth.getDefaultState();
  }

  _tick() {
    this.setState({
      autoVerifyCountDown: this.state.autoVerifyCountDown - 1,
    });
  }

  /**
   * Called when confirm code is pressed - we should have the code and verificationId now in state.
   */
  afterVerify = () => {
    const { codeInput, verificationId } = this.state;
    const credential = firebase.auth.PhoneAuthProvider.credential(
      verificationId,
      codeInput
    );

    // TODO do something with credential for example:
    firebase
      .auth()
      .signInWithCredential(credential)
      .then(user => {
        console.log('PHONE AUTH USER ->>>>>', user.toJSON());
        this.setState({ user: user.toJSON() });
      })
      .catch(console.error);
  };

  signIn = () => {
    const { phoneNumber } = this.state;
    this.setState(
      {
        error: '',
        started: true,
        autoVerifyCountDown: this.timeout,
      },
      () => {
        firebase
          .auth()
          .verifyPhoneNumber(phoneNumber)
          .on('state_changed', phoneAuthSnapshot => {
            console.log(phoneAuthSnapshot);
            switch (phoneAuthSnapshot.state) {
              case firebase.auth.PhoneAuthState.CODE_SENT: // or 'sent'
                // update state with code sent and if android start a interval timer
                // for auto verify - to provide visual feedback
                this.setState(
                  {
                    sent: true,
                    verificationId: phoneAuthSnapshot.verificationId,
                    autoVerifyCountDown: this.timeout,
                  },
                  () => {
                    if (this.state.auto) {
                      this._autoVerifyInterval = setInterval(
                        this._tick.bind(this),
                        1000
                      );
                    }
                  }
                );
                break;
              case firebase.auth.PhoneAuthState.ERROR: // or 'error'
                // restart the phone flow again on error
                clearInterval(this._autoVerifyInterval);
                this.setState({
                  ...PhoneAuth.getDefaultState(),
                  error: phoneAuthSnapshot.error.message,
                });
                break;

              // ---------------------
              // ANDROID ONLY EVENTS
              // ---------------------
              case firebase.auth.PhoneAuthState.AUTO_VERIFY_TIMEOUT: // or 'timeout'
                clearInterval(this._autoVerifyInterval);
                this.setState({
                  sent: true,
                  auto: false,
                  verificationId: phoneAuthSnapshot.verificationId,
                });
                break;
              case firebase.auth.PhoneAuthState.AUTO_VERIFIED: // or 'verified'
                clearInterval(this._autoVerifyInterval);
                this.setState({
                  sent: true,
                  codeInput: phoneAuthSnapshot.code,
                  verificationId: phoneAuthSnapshot.verificationId,
                });
                break;
              default:
              // will never get here - just for linting
            }
          });
      }
    );
  };

  renderInputPhoneNumber() {
    const { phoneNumber } = this.state;
    return (
      <View style={{ flex: 1 }}>
        <Text>Enter phone number:</Text>
        <TextInput
          autoFocus
          style={{ height: 40, marginTop: 15, marginBottom: 15 }}
          onChangeText={value => this.setState({ phoneNumber: value })}
          placeholder="Phone number ... "
          value={phoneNumber}
          keyboardType = 'phone-pad'
        />
        <Button
          title="Begin Verification"
          color="green"
          onPress={this.signIn}
        />
      </View>
    );
  }

  renderSendingCode() {
    const { phoneNumber } = this.state;

    return (
      <View style={{ paddingBottom: 15 }}>
        <Text style={{ paddingBottom: 25 }}>
          {`Sending verification code to '${phoneNumber}'.`}
        </Text>
        <ActivityIndicator animating style={{ padding: 50 }} size="large" />
      </View>
    );
  }

  renderAutoVerifyProgress() {
    const {
      autoVerifyCountDown,
      started,
      error,
      sent,
      phoneNumber,
    } = this.state;
    if (!sent && started && !error.length) {
      return this.renderSendingCode();
    }
    return (
      <View style={{ padding: 0 }}>
        <Text style={{ paddingBottom: 25 }}>
          {`Verification code has been successfully sent to '${phoneNumber}'.`}
        </Text>
        <Text style={{ marginBottom: 25 }}>
          {`We'll now attempt to automatically verify the code for you. This will timeout in ${autoVerifyCountDown} seconds.`}
        </Text>
        <Button
          style={{ paddingTop: 25 }}
          title="I have a code already"
          color="green"
          onPress={() => this.setState({ auto: false })}
        />
      </View>
    );
  }

  renderError() {
    const { error } = this.state;

    return (
      <View
        style={{
          padding: 10,
          borderRadius: 5,
          margin: 10,
          backgroundColor: 'rgb(255,0,0)',
        }}
      >
        <Text style={{ color: '#fff' }}>{error}</Text>
      </View>
    );
  }

  render() {
    const { started, error, codeInput, sent, auto, user } = this.state;
    return (
      <View
        style={{ flex: 1, backgroundColor: user ? 'rgb(0, 200, 0)' : '#fff' }}
      >
        <View
          style={{
            padding: 5,
            justifyContent: 'center',
            alignItems: 'center',
            flex: 1,
          }}
        >
          <Image
            source={{ uri: imageUrl }}
            style={{
              width: 128,
              height: 128,
              marginTop: 25,
              marginBottom: 15,
            }}
          />
          <Text style={{ fontSize: 25, marginBottom: 20 }}>
            Phone Auth Example
          </Text>
          {error && error.length ? this.renderError() : null}
          {!started && !sent ? this.renderInputPhoneNumber() : null}
          {started && auto && !codeInput.length
            ? this.renderAutoVerifyProgress()
            : null}
          {!user && started && sent && (codeInput.length || !auto) ? (
            <View style={{ marginTop: 15 }}>
              <Text>Enter verification code below:</Text>
              <TextInput
                autoFocus
                style={{ height: 40, marginTop: 15, marginBottom: 15 }}
                onChangeText={value => this.setState({ codeInput: value })}
                placeholder="Code ... "
                value={codeInput}
              />
              <Button
                title="Confirm Code"
                color="#841584"
                onPress={this.afterVerify}
              />
            </View>
          ) : null}
          {user ? (
            <View style={{ marginTop: 15 }}>
              <Text>{`Signed in with new user id: '${user.uid}'`}</Text>
            </View>
          ) : null}
        </View>
      </View>
    );
  }
}

/*
 { user ? (
 <View
 style={{
 padding: 15,
 justifyContent: 'center',
 alignItems: 'center',
 backgroundColor: '#77dd77',
 flex: 1,
 }}
 >
 <Image source={{ uri: successImageUri }} style={{ width: 100, height: 100, marginBottom: 25 }} />
 <Text style={{ fontSize: 25 }}>Signed In!</Text>
 <Text>{JSON.stringify(user)}</Text>
 </View>
 ) : null}
 */

// Example usage if handling here and not in optionalCompleteCb:
// const { verificationId, code } = phoneAuthSnapshot;
// const credential = firebase.auth.PhoneAuthProvider.credential(verificationId, code);

// Do something with your new credential, e.g.:
// firebase.auth().signInWithCredential(credential);
// firebase.auth().linkWithCredential(credential);
// etc ...

我仍然会收到此错误。

我生成了sha1 enter image description here 然后我复制我的项目 enter image description here 我在AndroidManifest.xml中检查过我有相同的包名。

4 个答案:

答案 0 :(得分:4)

我知道有时会有点烦恼再去一步一步,但通常是找到错误的更好方法。

不确切知道你正在使用的IDE,所以我用android Studio制作它,但你可以复制到你的。或者导入Android项目以在Android Studio中执行此操作

首先转到firebase控制台并检查您的包名称 enter image description here

现在在Android Studio中检查你的包是否真的相同,在AndroidManifest.xml中 enter image description here

如果不一样,你应该更改firebase,甚至启动一个新项目

下一步SHA-1

您可以使用此代码(不需要更改)keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

在Android Studio中打开终端(查看&gt;工具窗口&gt;终端)和复制/粘贴

enter image description here 复制SHA-1(建议在某个地方保存)

转到Firebase控制台设置(单击齿轮)

enter image description here

检查SHA-1 enter image description here

再次下载google-services.json

放入app文件夹(删除上一个) 你可以在android studio中使用“项目”视图

看到这个

enter image description here

这个问题的作用是什么(在上面的答案中从问题所有者那里复制)

运行项目时,需要从android studio生成SHA1!

  • 运行您的项目。
  • 点击Gradle菜单。
  • 展开Gradle Tasks树。
  • 双击android - &gt; signedReport,你会看到结果

对于Android studio 2.2 - 结果将在“运行”控制台下可用,但使用突出显示的切换按钮。

答案 1 :(得分:1)

如果您使用的是Android Studio,则可以将Firebase连接到您的帐户并自动设置相关性

工具 - &gt; Firebase - &gt;身份验证 - &gt;链接:“电子邮件和密码验证” - &gt;步骤1和2(并按照步骤2中的链接)

希望有所帮助

答案 2 :(得分:1)

我找到了解决方案 你需要在运行项目时从android studio生成SHA1!

  1. 运行您的项目。
  2. 点击Gradle菜单。
  3. 展开Gradle Tasks树。
  4. 双击android - &gt; signedReport,你会看到结果
  5. 对于Android studio 2.2 - 结果将在“运行”控制台下提供,但使用突出显示的切换按钮。

答案 3 :(得分:0)

如果一切正确

  • 包装名称
  • SHA1键
  • firebase配置

当然,这是因为您的测试方式。

您必须在真实设备上运行该应用,然后重试。