Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Phone auth failed: this app is not authorized to use Firebase Authentication #1039

Closed
adirzoari opened this issue May 1, 2018 · 27 comments
Closed
Labels
resolution: user Issue with users code or an issue that should be directed to Stack Overflow or the Discord server.

Comments

@adirzoari
Copy link

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

@adirzoari adirzoari changed the title react native with firebase phone auth validation failed Phone auth failed: this app is not authorized to use Firebase Authentication May 1, 2018
@chrisbianca
Copy link
Contributor

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.

@adirzoari
Copy link
Author

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

@chrisbianca
Copy link
Contributor

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.

@adirzoari
Copy link
Author

adirzoari commented May 1, 2018

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

@chrisbianca
Copy link
Contributor

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

@adirzoari
Copy link
Author

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

@chrisbianca
Copy link
Contributor

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.

@chrisbianca chrisbianca added the resolution: user Issue with users code or an issue that should be directed to Stack Overflow or the Discord server. label May 1, 2018
@RZulfikri
Copy link

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

@adirzoari
Copy link
Author

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

@numandev1
Copy link

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

@alexandranb
Copy link

Hi,

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

Thanks

@Manoj002
Copy link

@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

@ManigandanRaamanathan
Copy link

@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?

@Manoj002
Copy link

Manoj002 commented Dec 6, 2018

@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
Copy link

@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?

@Manoj002
Copy link

Manoj002 commented Dec 6, 2018

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

@devahmadbarham
Copy link

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

@badarshahzad
Copy link

@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! 👍 Thank you

@anastely
Copy link

anastely commented Nov 3, 2019

Any updates?

@mikehardy
Copy link
Collaborator

@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

@anastely
Copy link

anastely commented Nov 3, 2019

@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 :)

@antoinefotso
Copy link

@anastely yes Firebase will send an SMS to your users

@anastely
Copy link

anastely commented Nov 4, 2019

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

@mikehardy
Copy link
Collaborator

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

@BAIPAS-INC
Copy link

I had the same issue, but solved it by setting up SHA256 key. I had android seftynet feature enabled which requires you to set up SHA256 along with SHA1.

@saudkhanbpk
Copy link

i added both key sha 1 and sha 256 and also enable the play integraty api in google cloud console and the firebase is working with testing phone nmber and otp and not working with real number and sjowing this issue WARN Possible Unhandled Promise Rejection (id: 3):
Error: [auth/too-many-requests] We have blocked all requests from this device due to unusual activity. Try again later.

@shivamparvat
Copy link

I added both release sha1 and sha 256 keys and also added play integrity API also test in debug keys in both modes only GoogleSignin is working and signInWithPhoneNumber giving an error [Error: [auth/app-not-authorized] This app is not authorized to use Firebase Authentication. Please verify that the correct package name, SHA-1, and SHA-256 are configured in the Firebase Console.]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
resolution: user Issue with users code or an issue that should be directed to Stack Overflow or the Discord server.
Projects
None yet
Development

No branches or pull requests