Google登录的Android Firebase身份验证失败

时间:2016-10-06 15:47:09

标签: android firebase firebase-authentication google-signin

我从上到下跟着firebase documentation,并为我的应用实施了一个简单的Google登录选项。但是,当我尝试登录时,该流程在选择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
       }
}

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

的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方法:

点击 Google登录按钮后会调用SignIn方法

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

onActivityResult:

在单击按钮后收到结果时会调用onActivityResult。这是发生错误的地方:

    @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条件下中断。

    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_services.json文件添加到/ app目录

     

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

这是我的傻瓜:

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

4 个答案:

答案 0 :(得分:5)

在我之前使用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应用。

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

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

答案 1 :(得分:0)

检查google API console

中是否启用了“Identity Toolkit API”

答案 2 :(得分:0)

转到firebase控制台并首先启用登录提供程序。 https://console.firebase.google.com/u/2/project/ipay-71f01/authentication/providers

我有同样的问题,但这是我的解决方案。 感谢

答案 3 :(得分:0)

确保您已输入签名密钥库的SHA1。 这是指南https://developers.google.com/android/guides/client-auth

你必须找到两个目录, 1.已安装JDK的目录 2. .android

如果您使用的是Windows,'。android'文件夹可能放在'C:\ Users \ username \'中,而JDK目录可能放在'C:\ Users \ Program files \ java \'中。< / p>

在我的情况下,我的操作系统是Windows,所以首先我正在寻找我的jdk文件夹。

在'jdk_folder \ bin \'中你会找到'keytool.exe'并且我使用了这个命令

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

然后,复制SHA1密钥并粘贴到firebase控制台(设置 - 一般 - 我的应用程序 - SHA证书指纹(?)'(我住在韩国,因此菜单的名称可能与我不同)并且它有效:)