简体   繁体   English

Google Signin的Android Firebase身份验证失败

[英]Android Firebase Authentication for Google Signin fails

I followed the firebase documentation from top to bottom and implemented a simple google Sign in option to my app. 我从上到下跟踪了firebase文档 ,并为我的应用程序实现了一个简单的谷歌登录选项。 However, when I try to signin, the process halts after selecting a google account and results in an error inside the onActivityResult method: 但是,当我尝试登录时,该流程在选择Google帐户后停止,并导致onActivityResult方法内部出错:

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

The code breaks at the if (result.isSuccess()) condition. 代码在if (result.isSuccess())条件下中断。 To elaborate further, here's the complete code I implemented after going through the doc: 进一步详细说明,这是我在完成文档后实现的完整代码:

onCreate: 的onCreate:

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

signIn method: signIn方法:

The SignIn method gets called when the Google Signin button is clicked : 单击Google Signin按钮时会调用SignIn方法:

    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. 单击按钮后收到结果时,将调用onActivityResult。 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
            }
        }
    }

Handling Firebase Login code for Google: 处理Google的Firebase登录代码:

This method never gets called because the code breaks at the onActivityResult condition. 永远不会调用此方法,因为代码在onActivityResult条件下中断。

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

Checklist : 清单

Yes, I added the google_services.json file to the /app directory 是的,我将google_services.json文件添加到/ app目录

Yes, I created a new OAuth Client Key in the Google Credentials page 是的,我在Google凭据页面中创建了一个新的OAuth客户端密钥

Here's my gradle: 这是我的傻瓜:

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'

And.. 和..

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

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. 在我之前使用Firebase FriendlyChat的测试应用中,我在登录时遇到了类似的失败,但是我已经通过Google API控制台( https://console.developers.google.com/apis/credentials?project= )解决了这个问题,然后下载了“client_secret.json”(在我的情况下,我需要为您的Android客户端重命名下载的文件名“client_secret_xxxxx.json”),将此文件放在AndroidStudio项目的“/ src / main / resources”下(创建“resources”文件夹)如果不存在,那么尝试再次编译并运行您的Android应用程序。

Summary: you need 2 json files : "google-services.json" from Firebase Console and "client_secret.json" from Google API Console. 摘要:您需要2个json文件:Firebase Console中的“google-services.json”和Google API控制台中的“client_secret.json”。

Hope this solve your problem. 希望这能解决你的问题。

检查是否在Google API控制台中启用了“Identity Toolkit API”

Go to the firebase console and enable the sign in provider first. 转到firebase控制台并首先启用登录提供程序。 https://console.firebase.google.com/u/2/project/ipay-71f01/authentication/providers https://console.firebase.google.com/u/2/project/ipay-71f01/authentication/providers

I had the same issue but this was the solution for me. 我有同样的问题,但这是我的解决方案。 Thanks 谢谢

Make sure that you have entered the SHA1 of your signing keystore. 确保您已输入签名密钥库的SHA1。 Here's the guide https://developers.google.com/android/guides/client-auth 以下是https://developers.google.com/android/guides/client-auth指南

You have to find two directories, 1. a directory where JDK have been installed 2. .android 您必须找到两个目录,1。已安装JDK的目录2. .android

If you are using Windows, '.android' folder might be placed in 'C:\\Users\\username\\', and JDK directory might be placed in like 'C:\\Users\\Program files\\java\\'. 如果您使用的是Windows,'。android'文件夹可能放在'C:\\ Users \\ username \\'中,而JDK目录可能放在'C:\\ Users \\ Program files \\ java \\'中。

In my case, my OS is Windows, so first i was looking for my jdk folder. 在我的情况下,我的操作系统是Windows,所以首先我正在寻找我的jdk文件夹。

In 'jdk_folder\\bin\\' you would find 'keytool.exe' and I used this command 在'jdk_folder \\ bin \\'中你会找到'keytool.exe'并且我使用了这个命令

'.\\keytool -exportcert -list -v -alias androiddebugkey -keystore C:\\Users\\sgc109\\ .android\\debug.keystore'. '。\\ keytool -exportcert -list -v -alias androiddebugkey -keystore C:\\ Users \\ sgc109 \\ .android \\ debug.keystore'。

Then, copy SHA1 key and paste to firebase console(setting - general - my app - SHA certificate finger print(?)' (I live in Korea, so names of menu could be different with me) and it works :) 然后,复制SHA1密钥并粘贴到firebase控制台(设置 - 一般 - 我的应用程序 - SHA证书指纹(?)'(我住在韩国,所以菜单的名称可能与我不同),它的工作原理:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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