简体   繁体   中英

Firebase Authentication error in android

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.

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.

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

这里

在此输入图像描述

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);
    }
}

}

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.

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

I also have encoutered same problem. Nothing helped including playing with rules and gradle addings, enablings and so these. The only what was the solution is in onCreate():

...                                                           
    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApiKey("AIzaSyA61lkklrz_K_vXsrUUiug9LwImK3sg26bE")//https://console.developers.google.com/apis/credentials?project=korisanjish-92e92
            .setApplicationId("uz.man.speach.gapi")
            .setDatabaseUrl("https://korisanjish-92e92.firebaseio.com/")
            .build();
     fbApp = FirebaseApp.initializeApp(getApplicationContext(), options, "SpeachGAPIMaximTest");
    fbDB = FirebaseDatabase.getInstance(fbApp);
    fbDB.setPersistenceEnabled(true);                                   
     ...

And in on onStart():

...                                                                        
    mAuth = FirebaseAuth.getInstance(fbApp);//
     List<FirebaseApp> lLcl= FirebaseApp.getApps(this);
    for(FirebaseApp fb : lLcl){
        l.a(fb.getName());
    }

    showWheel();
    mAuth.signInWithEmailAndPassword("rusti@gmail.com", "U$pe$hn11Proekt")
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        l.a( "signInWithEmail:success");
                        FirebaseUser currentUser = mAuth.getCurrentUser();

                        if(currentUser==null)
                            l.a(434343);
                        else
                            l.a( currentUser.getEmail());
                        stopWheel();

                    } else {
                        // If sign in fails, display a message to the user.
                        l.a( task.getException());
                        l.a(task.getException().getMessage());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            });                                                           
         ...

And in a method:

private void sendToFireBase() {
    MainActivity activityLcl = (MainActivity) getActivity();
    DatabaseReference mDatabase = activityLcl.getFbDB().getReference();
    String sLcl = (String) hashMap.get("Item ID");
    User userLcl = new User(altitudeDouble, location.getLongitude(), location.getLatitude(), urlString,
            textString, languageString, preceededIdString, sLcl);
    //Double altitude, Double longitude, Double latitude, String url, String text, String locale, String preceededId

    FirebaseAuth mAuthLcl = activityLcl.getAuth();
    activityLcl.showWheel();
    mDatabase.child("users").child(mAuthLcl.getUid()).setValue(userLcl, new DatabaseReference.CompletionListener() {
        public void onComplete(DatabaseError error, DatabaseReference ref) {
            MainActivity activityLcl = (MainActivity) getActivity();
            String s2Lcl = "";
            if (null == error) {
                s2Lcl = "Uploaded";
            } else
                s2Lcl = error.getDetails();
            activityLcl.showMessage("Value was set. Status = " + s2Lcl);

            l.a("Value was set. Error = " + s2Lcl);
            activityLcl.stopWheel();
        }
    });
}

Another error I did in strings.xml the app_name was wrong in a letter.

try all the above answers though it still not working replace google-services.json file with new google-services.json . it had worked for me do it right now.

I know it's an old question but I recently faced a similar problem and figured out how to solve it. In my case, my problem relied in how I created the SignInIntent passed to startActivityForResult .

Like you did, I also correctly configured the Google authentication method in Firebase Console and copied the example code provided in the Firebase Documentation page ( https://firebaseopensource.com/projects/firebase/firebaseui-android/auth/README.md ).

However, I was getting the same error you got every time I tried to connect. Then I realized that I wasn't activating the Google Provider when calling startActivityForResult . At first, I tried the code below with no success.

startActivityForResult(
    AuthUI.getInstance()
          .createSignInIntentBuilder()
          .build(),
           RC_SIGN_IN);

Then I changed it to the code below and got it to work!

startActivityForResult(
    AuthUI.getInstance()
        .createSignInIntentBuilder()
        .setAvailableProviders(Arrays.asList(                        
                AuthUI.IdpConfig.GoogleBuilder().build()))
        .build(), RC_SIGN_IN)

Note that the first code snippet isn't using the Google Provider so it relied on User/Password authentication method. If you enable this method in the Firebase Console, then this snippet will work perfectly.

I had this same issue working on a Nativescript app and nothing fixed it until I DELETED my node_modules and platforms folders and rebuilt the project . That fixed my issue. In other words (and this may apply for other frameworks other than TNS or even mobile), delete you generated files and rebuild to regenerate them.

Hope this helps someone! I know it took me a long time before trying this :p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM