用Firebase电话身份验证失败响应本机 [英] react native with firebase phone auth validation failed

查看:69
本文介绍了用Firebase电话身份验证失败响应本机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过与Firebase电话身份验证进行本地响应react-native-firebase文档 我得到这个错误

I'm trying to make react native with firebase phone auth through react-native-firebase docs and I get this error

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

Error: This app is not authorized to use Firebase Authentication. Please verifythat the correct package name and SHA-1 are configured in the Firebase Console. [ App validation failed ]

我已经创建了debug.keystore

I have already created debug.keystore

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

然后我得到了SHA1

then I get the SHA1

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

并粘贴到firebase控制台中,然后下载google-services.json并添加到我的react native应用中. 然后在我的代码中写了

and paste into firebase console and download the google-services.json and add to my react native app. then into my code I wrote

    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中签入了相同的包名.

I generated sha1 then I copy in my project I checked in AndroidManifest.xml I have the same packagename.

推荐答案

我知道有时有时会有些烦人,请重新进行逐步操作,但这通常是查找错误的更好方法.

I know that sometimes is a little bit annoying go to step by step again, but normally is the better way to find the error.

不完全知道您正在使用的IDE,所以我使用android Studio来制作它,但是您可以将其复制到自己的IDE中.或导入Android项目以在Android Studio中执行此操作

Don't know exactly the IDE that you are using, so I make this with android Studio, but you can copy to yours. Or import the Android project to do this in Android Studio

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

First go to your firebase console and check your package name

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

Now in Android Studio check if your package is really the same, inside AndroidManifest.xml

如果不一致,则应更改Firebase,甚至启动新项目

下一步SHA-1

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

You can use exactly this code (don't need to change) keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

在Android Studio中,打开终​​端"(视图>工具窗口">终端"),然后复制/粘贴

In Android Studio open the Terminal (View > Tool Windows > Terminal) and Copy/Paste

复制SHA-1(建议保存在某个位置)

Copy the SHA-1 (suggest to save in some place)

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

Go to Firebase console settings (click on the gear)

检查SHA-1

再次下载google-services.json.

放入app文件夹(删除上一个) 您可以在android studio中使用项目"查看

Put in the app folder (Delete the previous one) You can see this in android studio using the "project" view

该问题的解决方法(从问题所有者的答案中复制)

And what work for this question (copy from the question owner in a answer above)

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

You need to generate SHA1 from android studio when you run the project!

  • 运行您的项目.
  • 单击右侧的Gradle菜单.
  • 展开Gradle Tasks树.
  • 双击android-> signingReport,您将看到结果

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

For Android studio 2.2 - result will be available under Run console but use highlighted toggle button.

这篇关于用Firebase电话身份验证失败响应本机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆