2

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

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 ]

I have already created debug.keystore

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

then I get the SHA1

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

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 ...

and I still get this error.

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

Community
  • 1
  • 1
Manspof
  • 598
  • 26
  • 81
  • 173

4 Answers4

6

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.

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

First go to your firebase console and check your package name enter image description here

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

If is not the same, you should change in firebase, even launch a new project

Next step SHA-1

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

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

enter image description here Copy the SHA-1 (suggest to save in some place)

Go to Firebase console settings (click on the gear)

enter image description here

Check the SHA-1 enter image description here

download the google-services.json again.

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

enter image description here

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

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

  • Run your project.
  • Click on Gradle menu where it on right-hand side.
  • Expand Gradle Tasks tree.
  • Double click on android -> signingReport and you'll see the result

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

Sampath
  • 63,341
  • 64
  • 307
  • 441
Canato
  • 3,598
  • 5
  • 33
  • 57
  • Hey, first thank you for your time and great explanation. I did exactly as you described before, it still show me same issue. I checked step by step. I generate debug.keystore with other commands because yours not works for me. I generate with keytool -genkey -v -keystore debug.keystore -storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000, then show the keystore with your command. – Manspof May 01 '18 at 11:06
  • I'm using react native with IDE visual studio code. I edited my post and add the generate sha1 and photo from firebase console.. just asking, in your screenshot of sha1, i see it's version 1 and mine is version 3. what the version says? – Manspof May 01 '18 at 11:15
  • @AdirZoari research a lot and did not found about this version =|. Maybe work it to create a new question! And thanks for the Right click. Will copy your answer in mine to be more correct. – Canato May 01 '18 at 22:26
  • thank you for your time. I will award your answer when it enable. I have 2 new issues with firebase firebase auth and fcm, if u have time https://stackoverflow.com/questions/50120751/firebase-auth-phone-not-send-sms-to-user-that-already-aunthenticated https://stackoverflow.com/questions/50087894/react-native-with-firebase-fcm/50124583#50124583 – Manspof May 01 '18 at 22:29
  • @AdirZoari I am getting the same issue. Tried everything mention in the approved answer but still its getting failed. And I too am getting `version 3`. How did you resolve your issue? – Shubhaw Kumar Jul 17 '19 at 08:28
  • Hey @Canato i just follow all the steps but i see this message again `Error: [auth/app-not-authorized] This app is not authorized to use Firebase Authentication. Please verify that the correct package name and SHA-1 are configured in the Firebase Console.` – DevAS Nov 03 '19 at 16:30
1

If you use Android Studio you can connect Firebase to your account and set the dependencies automatically

Tools -> Firebase -> Authentication -> Link:"Email and password authentication" -> Step 1 and 2 (And follow the link in Step 2)

Dharman
  • 30,962
  • 25
  • 85
  • 135
Roman
  • 318
  • 2
  • 8
1

I found a solution you need to generate SHA1 from android studio when you run the project!

  1. Run your project.
  2. Click on Gradle menu.
  3. Expand Gradle Tasks tree.
  4. Double click on android -> signingReport and you'll see the result

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

Manspof
  • 598
  • 26
  • 81
  • 173
  • Hey @AdirZoari I dont have in Android Studio "Gradle menu" ! , and error `Error: [auth/app-not-authorized] This app is not authorized to use Firebase Authentication` is gone when I write a phone number for a test in firebase console ! so my Q is when I release the app for production Firebase will send an SMS message with Code to users? – DevAS Nov 03 '19 at 19:23
0

If everything is correct

  • package name
  • SHA1 key
  • firebase configuration

Certainly, that is because of the way you test.

You have to run the app on a real device then try again.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Mr Special
  • 1,576
  • 1
  • 20
  • 33