本文介绍了适用于Google登录的Android Firebase身份验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从头到尾遵循 firebase文档并实施了我的应用程序的一个简单的google登录选项.但是,当我尝试登录时,选择Google帐户后该过程将暂停,并在onActivityResult方法内导致错误:

I followed the firebase documentation from top to bottom and implemented a simple google Sign in option to my app. However, when I try to signin, the process halts after selecting a google account and results in an error inside the onActivityResult method:

if (requestCode == RC_SIGN_IN) {
       GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
       if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
       } else {
            //THE CODE BREAKS HERE
            // Google Sign In failed, update UI appropriately
       }
}

代码在if (result.isSuccess())条件下中断.为了进一步详细说明,这是我在阅读文档后实现的完整代码:

The code breaks at the if (result.isSuccess()) condition. To elaborate further, here's the complete code I implemented after going through the doc:

在创建时:

public class TestLogin extends AppCompatActivity {

    private SignInButton mGoogleBtn;
    private static int RC_SIGN_IN = 226;
    private GoogleApiClient mGoogleApiClient;
    private  String TAG = "Checkmate";
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_login);

        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() != null){
                    //success
                }
            }
        };

        mGoogleBtn = (SignInButton) findViewById(R.id.googleBtn);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken("MY_CLIENT_ID-MY_CLIENT_ID.apps.googleusercontent.com")
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
                .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        //Failed
                    }
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        mGoogleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                statusMessage.setText("Loading..");
                signIn();
            }
        });
    }

登录方法:

点击 Google登录按钮时,将调用SignIn方法:

The SignIn method gets called when the Google Signin button is clicked:

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

onActivityResult:

onActivityResult.这是发生错误的地方:

onActivityResult is called when the result is received after clicking the button. This is where the error occurs:

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

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                //THE CODE BREAKS HERE
                // Google Sign In failed, update UI appropriately
            }
        }
    }

处理Google的Firebase登录代码:

此方法从不调用,因为代码在onActivityResult条件下中断.

This method never gets called because the code breaks at the onActivityResult condition.

    private void firebaseAuthWithGoogle(final 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) {

                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                            Toast.makeText(TestLogin.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

清单:

是的,我在Google凭据页面中创建了一个新的OAuth客户端密钥

Yes, I created a new OAuth Client Key in the Google Credentials page

这是我的礼物:

dependencies {
    compile 'com.google.android.gms:play-services:9.6.1'
    compile 'com.google.firebase:firebase-core:9.6.1'
    compile 'com.google.firebase:firebase-database:9.6.1'
    compile 'com.google.firebase:firebase-auth:9.6.1'
    compile 'com.google.firebase:firebase-storage:9.6.1'
}
apply plugin: 'com.google.gms.google-services'

并且..

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

推荐答案

在我以前使用Firebase FriendlyChat的测试应用程序中,我在登录时遇到了类似的失败,但是我已经通过使用Google API控制台( https://console.developers.google.com/apis/credentials?project= )然后为您的Android客户端下载"client_secret.json"(在我的情况下,我需要重命名下载的文件名"client_secret_xxxxx.json"),将此文件放在AndroidStudio项目的"/src/main/resources"下(创建"resources" 文件夹(如果不存在)),然后尝试重新编译并运行您的Android应用.

In my previous test app using Firebase FriendlyChat, I have encountered similar failure in Sign In, but I have solved it by going Google API console (https://console.developers.google.com/apis/credentials?project=) then download "client_secret.json" (in my case, I need to rename the downloaded filename "client_secret_xxxxx.json") for your Android client, put this file in your AndroidStudio project under "/src/main/resources" (create "resources" folder if not exist) then try to compile and run your Android app again.

摘要:您需要2个json文件:Firebase控制台中的"google-services.json"和Google API控制台中的"client_secret.json".

Summary: you need 2 json files : "google-services.json" from Firebase Console and "client_secret.json" from Google API Console.

希望这可以解决您的问题.

Hope this solve your problem.

这篇关于适用于Google登录的Android Firebase身份验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 12:19