【问题标题】:react native with firebase phone auth validation failed使用firebase电话身份验证验证失败
【发布时间】:2018-10-09 16:00:40
【问题描述】:

我正在尝试通过 react-native-firebase docs 使用 Firebase 电话身份验证做出本机反应 我得到这个错误

错误:此应用无权使用 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 并添加到我的 react native 应用程序中。 然后进入我写的代码

    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 然后我复制到我的项目中 我检查了 AndroidManifest.xml 我有相同的包名。

【问题讨论】:

  • 您是否真的在控制台中在线启用了它?
  • 用手机登录?是的,我启用了
  • 您使用的是物理设备进行连接,对吧?
  • 是的。我在物理设备中使用
  • 为什么你的项目有两个 SHA-1? @AdirZoari

标签: android firebase react-native


【解决方案1】:

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

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

首先转到您的 Firebase 控制台并检查您的软件包名称

现在在 Android Studio 中检查您的包是否真的相同,在 AndroidManifest.xml 中

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

下一步 SHA-1

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

在 Android Studio 中打开终端(查看 > 工具窗口 > 终端)并复制/粘贴

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

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

检查 SHA-1

再次下载google-services.json

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

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

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

  • 运行您的项目。
  • 点击右侧的 Gradle 菜单。
  • 展开 Gradle 任务树。
  • 双击android -> signingReport 你会看到结果

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

【讨论】:

  • 嘿,首先感谢您的宝贵时间和精彩的解释。我完全按照你之前的描述做了,它仍然显示同样的问题。我一步一步检查。我使用其他命令生成 debug.keystore ,因为您的命令不适合我。我用keytool -genkey -v -keystore debug.keystore -storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000 生成,然后用你的命令显示keystore。
  • 我将 react native 与 IDE Visual Studio 代码一起使用。我编辑了我的帖子并从 firebase 控制台添加了生成 sha1 和照片.. 只是问,在你的 sha1 截图中,我看到它是第 1 版,而我的是第 3 版。版本说什么?
  • @AdirZoari 研究了很多,没有找到关于这个版本的信息=|。也许可以创建一个新问题!并感谢您的右键单击。将您的答案复制到我的答案中以更正确。
  • 感谢您的宝贵时间。当它启用时,我会奖励你的答案。如果你有时间stackoverflow.com/questions/50120751/…stackoverflow.com/questions/50087894/…,我有 2 个关于 firebase firebase auth 和 fcm 的新问题
  • @AdirZoari 我遇到了同样的问题。尝试了批准答案中提到的所有内容,但仍然失败。我也收到version 3。您是如何解决问题的?
【解决方案2】:

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

  1. 运行您的项目。
  2. 点击 Gradle 菜单。
  3. 展开 Gradle 任务树。
  4. 双击android -> signingReport 你会看到结果

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

【讨论】:

  • 嘿 @AdirZoari 我在 Android Studio 中没有“Gradle 菜单”! ,并且当我在 firebase 控制台中写一个电话号码进行测试时,错误 Error: [auth/app-not-authorized] This app is not authorized to use Firebase Authentication 消失了!所以我的问题是当我发布用于生产的应用程序时,Firebase 会向用户发送带有代码的 SMS 消息?
【解决方案3】:

如果您使用 Android Studio,您可以将 Firebase 连接到您的帐户并自动设置依赖项

工具 -> Firebase -> 身份验证 -> 链接:“电子邮件和密码身份验证” -> 第 1 步和第 2 步(并点击第 2 步中的链接)

【讨论】:

  • 嘿,roman,我正在使用 react native 和 IDE 视觉工作室代码
  • 我猜您设置了依赖项以使用 google json 文件? link
  • 其实这对我来说是最好的解决方案。
【解决方案4】:

如果一切都正确

  • 包名
  • SHA1 密钥
  • firebase 配置

当然,那是因为你的测试方式。

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

【讨论】:

    猜你喜欢
    • 2018-12-06
    • 2020-05-22
    • 2021-07-13
    • 1970-01-01
    • 2019-03-11
    • 2018-03-27
    • 2017-11-27
    相关资源
    最近更新 更多