React-native-firebase: Phone auth failed: this app is not authorized to use Firebase Authentication

Created on 1 May 2018  路  24Comments  路  Source: invertase/react-native-firebase

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:Usersadirz.androiddebug.keystore" -storepass android -keypass android
and paste the sha1 into firebase console (you can see in the photos through the links)
https://i.stack.imgur.com/06zFu.jpg
https://i.stack.imgur.com/jFxI4.jpg

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.

User Issue

Most helpful comment

@RZulfikri yes.
open your react native project into android studio and then:

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

All 24 comments

Please read the documentation on certificates: https://developers.google.com/android/guides/client-auth

You do not need to generate a certificate for debug - it uses the default android keystore.

Hey, it's not use the default android keystore..

My point is, you don't need to generate a debug keystore, just use the default android keystore and you won't have any issues.

but it ask me to generate sha1 for use phone auth, when i add app in firebase console

Read the link I sent you: https://developers.google.com/android/guides/client-auth

You can generate a SHA1 using the following command for debug:

keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

that's what I did @chrisbianca, still get issues. I stuck with it 2 days.

Sorry, but this isn't a react-native-firebase issue, I'd suggest following the official documentation from start to finish for phone auth and making sure you've done everything it says.

Beyond that I'd turn to Stack Overflow to see if anybody has some time to help, but they will only suggest what I've already suggested.

hi, i have same issue. Have you solve it ?

@RZulfikri yes.
open your react native project into android studio and then:

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

i have same issue
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.

i have already added SHA-1 package name to firebase but could not resolve this error

Hi,

I have the same issue. Has anyone found a solution?

Thanks

@chrisbianca, hello mate thanks for this awesome library
This works fine on my device but when i share the apk and try it on different devices i get the same error, im even getting the otp on my device but on different its not working

@chrisbianca, hello mate thanks for this awesome library
This works fine on my device but when i share the apk and try it on different devices i get the same error, im even getting the otp on my device but on different its not working

@Manoj002 can you please share the code that you are using?

@ManigandanRaamanathan, thanks for your reply mates,
I got it solved by yesterday, the problem was the sha1 key, it was debug sha1 key, instead I generated a build sha1 key and it worked perfectly.

@ManigandanRaamanathan, thanks for your reply mates,
I got it solved by yesterday, the problem was the sha1 key, it was debug sha1 key, instead I generated a build sha1 key and it worked perfectly.

@Manoj002 may I get the code that you are using for my reference?

Keytool -list -v -keystore (now this is your relative path to key.keystore[generated while creating your signed apk] file without parenthesis) -alias (here you need to give alias name which you provided in gradle.properties file I guess default is my-key-alias)

Hope this helps

you need to know exactly key for release app you can check by use google play console try upload your app and you will display the sha-1

@RZulfikri yes.
open your react native project into android studio and then:

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

You save my day! :+1: Thank you

Any updates?

@anastely There will typically never be updates on closed issues. If you're experiencing a problem please make sure you've followed all the steps in the relevant documentation, then open a new issue following the template

@mikehardy thanks, I just have one small question?
I add SHA-1 "debug" firebase console App,
and in Sign-in method _Phone numbers for testing_ I add my number and Verification code and yeah its work, but that's right when I release the app in production?
Firebase will send an SMS to our users?
Sorry if that's question is humble :)

@anastely yes Firebase will send an SMS to your users

@antoinefotso Great! should i change something in my code Or firebase app settings?

There are so many things that can go wrong I wouldn't trust it until I had tried it on my own handset. But yes if you've at least got a testing phone number / code working you are close to success. One thing I'll note is that in my primary user country at least (Ecuador) I see varying performance across the competing carriers with regards to delivery of the SMS. One carrier is reliable and fast except if the number was recently ported then it fails, one is slow but reliable, one is unreliable. So don't consider SMS auth as the only way to do things, it can fail because of carrier behavior even when you've done everything right

Was this page helpful?
0 / 5 - 0 ratings