Firebase Authentication error in android

26,332

Solution 1

As you error said, you need to enable authentication in your Firebase console.

This can be done, accesing your project -> authentication meniu, SIGN-IN METHOD -> and then enable the desired authentication type.

Solution 2

You must allow firebase authentication from firebase, with email or facebook or other else

Firebase console -> Authentication -> Sign-in Method, and enable a method of signing in that your app will use

here

enter image description here

Full example of AuthActivity class code here:

package com.<you_domain>.<your_application_name>;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

public class AuthActivity extends AppCompatActivity
    implements GoogleApiClient.OnConnectionFailedListener,
    View.OnClickListener{

private Context authActivity;

private static int RC_SIGN_IN = 1;
private static String TAG = "AUTH_ACTIVITY";
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

private AlertDialog alertDialog;

private android.app.AlertDialog splashDialog;

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    authActivity = this;

    setContentView(R.layout.auth_activity);

    Window window = this.getWindow();

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
    }

    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    int gpsAvail = api.isGooglePlayServicesAvailable(authActivity);

    if(Connection.isInternetConnected(authActivity)){

        if(gpsAvail == ConnectionResult.SUCCESS){

        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                FirebaseUser user = firebaseAuth.getCurrentUser();

                if(user != null){
                    Log.d("AUTH", "user logged in: " + user.getEmail());
                }else{
                    Log.d("AUTH", "user logged out.");
                }
            }
        };

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.
                DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(authActivity)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        findViewById(R.id.sign_in_btn).setOnClickListener(this);

    }else if(gpsAvail == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED){

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(authActivity);

        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setTitle("Google Play Services out of date");
        alertDialogBuilder.setMessage("Your Google Play Services version is out of date. " +
                "Please update it and continue.");
        alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);

        alertDialogBuilder.setPositiveButton(" UPDATE ", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int id)
            {

                String url = "https://play.google.com/store/apps/" +
                        "details?id=com.google.android.gms";
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);

            }
        });

        alertDialog = alertDialogBuilder.create();

        alertDialog.setOnShowListener( new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface arg0) {
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                        .setTextColor(getColor(authActivity, R.color.colorPrimary));
            }
        });

        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                finish();
            }
        });

        alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                finish();
            }
        });

        alertDialog.show();

    }else{

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(authActivity);

        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setTitle("Google Play Services needed");
        alertDialogBuilder.setMessage("You need Google Play Services in order to proceed. " +
                "Please install the latest version.");
        alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);

        alertDialogBuilder.setPositiveButton(" INSTALL ", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int id)
            {

                String url = "https://play.google.com/store/apps/" +
                        "details?id=com.google.android.gms";
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);

            }
        });

        alertDialog = alertDialogBuilder.create();

        alertDialog.setOnShowListener( new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface arg0) {
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                        .setTextColor(getColor(authActivity, R.color.colorPrimary));
            }
        });

        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                finish();
            }
        });

        alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                finish();
            }
        });

        alertDialog.show();

    }

}else {

    try {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(authActivity);

        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setTitle("No internet connection");
        alertDialogBuilder.setMessage("Internet not available. " +
                "Please check your internet connectivity and try again.");
        alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);

        alertDialogBuilder.setPositiveButton(" OK ", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int id)
            {
                dialog.cancel();
            }
        });

        alertDialog = alertDialogBuilder.create();

        alertDialog.setOnShowListener( new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface arg0) {
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                        .setTextColor(getColor(authActivity, R.color.colorPrimary));
            }
        });

        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                finish();
            }
        });

        alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                finish();
            }
        });

        alertDialog.show();

    }
    catch(Exception e)
    {
        Log.d("Connection", "Show Dialog: " + e.getMessage());
    }

}

}

@Override
protected void onStart() {
    super.onStart();
    if(mAuthListener != null) {
        mAuth.addAuthStateListener(mAuthListener);
    }
}

@Override
protected void onStop() {
    super.onStop();
    if(mAuthListener != null){
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == RC_SIGN_IN){

        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

        if(result.isSuccess()){
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);

        }else{
            Log.d(TAG, "Google Login Failed");

            Toast.makeText(authActivity, "Sign in failed.", Toast.LENGTH_LONG).show();

        }

    }

}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct){

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d("AUTH", "signInWithCredential:oncomplete: " + task.isSuccessful());

                    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

                    if(user != null){

                        Intent intent = new Intent(AuthActivity.this, MainActivity.class);
                        startActivity(intent);
                        //splashDialog.dismiss();
                        splashDialog.cancel();

                        Toast.makeText(authActivity, "Successfully signed in",
                                Toast.LENGTH_LONG).show();

                        finish();

                    }

                }
            });

}

private void signIn(){
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    Log.d(TAG, "Connection failed.");

}

@Override
public void onClick(View view) {

    switch(view.getId()){

        case R.id.sign_in_btn:

            splashDialog = ProgressDialog.show(this, null, null);
            ProgressBar spinner = new android.widget.ProgressBar(this, null,
                    android.R.attr.progressBarStyle);
            spinner.getIndeterminateDrawable().setColorFilter(getColor(this,
                    R.color.colorPrimary), android.graphics.PorterDuff.Mode.SRC_IN);
            splashDialog.getWindow().setBackgroundDrawable(
                    new ColorDrawable(android.graphics.Color.TRANSPARENT));
            splashDialog.setContentView(spinner);
            splashDialog.setCancelable(false);

            signIn();

            break;

    }

}

@Override
public void onDestroy() {
    super.onDestroy();

    if (splashDialog != null) {
        splashDialog.cancel();
        splashDialog = null;
    }

}

@SuppressWarnings("deprecation")
public static int getColor(Context context, int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 23) {
        return ContextCompat.getColor(context, id);
    } else {
        return context.getResources().getColor(id);
    }
}

}

Solution 3

Following steps worked for me

  1. Go to Firebase Console and enable firebase auth for desired sign in method (mostly its "email and password" and "anynomous"
  2. Download your google-services.json file from console replace it with the existing one
  3. Rebuild your project

It worked for me and I hope It'll work for you too.

P.S: I'm adding this answer because none of the other answers mentioned replacing the json file, which I think actually did the work for me.

Share:
26,332
manjiri
Author by

manjiri

Updated on March 31, 2020

Comments

  • manjiri
    manjiri about 4 years

    Here is screen shot I am trying to sign in from google using firebase authentication at that time in my project there is a error

    com.google.firebase.auth.FirebaseAuthException: This operation is not allowed. You must enable this service in the console. and also it says ERROR_OPERATION_NOT_ALLOWED

    This operation is not allowed. You must enable this service in the console.