谷歌登录验证失败

Posted

技术标签:

【中文标题】谷歌登录验证失败【英文标题】:google sign in authentication failed 【发布时间】:2017-07-02 05:55:00 【问题描述】:

我想在我的应用程序中集成 Google 登录,但它没有让我继续进行其他活动,它显示模拟器中唯一的身份验证失败,但是当我在真实设备上测试它时,应用程序在单击 google 登录按钮时停止。下面是我的代码

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
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.SignInButton;
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 googleact extends AppCompatActivity 

SignInButton button;
FirebaseAuth firebaseauth;
private final static int RC_SIGN_IN=2;
GoogleApiClient mGoogleApiClient;
FirebaseAuth.AuthStateListener mAuthListener;


@Override
protected void onStart() 
    super.onStart();
    firebaseauth.addAuthStateListener(mAuthListener);


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


    button =(SignInButton) findViewById(R.id.googlebtn);
   firebaseauth = FirebaseAuth.getInstance();

    button.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            signIn();
        
    );

    mAuthListener=new FirebaseAuth.AuthStateListener() 
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) 
            if (firebaseAuth.getCurrentUser() !=null)

                startActivity(new Intent(googleact.this, gprofile.class));
            
        
    ;

    // Configure Google Sign In
    GoogleSignInOptions gso = new 
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();


        // Build a GoogleApiClient with access to the Google Sign-In API and 
the
// options specified by gso.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, new 
    GoogleApiClient.OnConnectionFailedListener() 
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult 
    connectionResult) 
                    Toast.makeText(googleact.this,"something went wrong", 
    Toast.LENGTH_SHORT).show();
                
            )
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();




// Configure Google Sign In
//GoogleSignInOptions gso = new 
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  //     .requestIdToken(getString(R.string.default_web_client_id))
      //  .requestEmail()
      //  .build();


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


@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 
            Toast.makeText(googleact.this,"AUTH WENT WRONG", 
Toast.LENGTH_SHORT).show();
        
    


    private void firebaseAuthWithGoogle(GoogleSignInAccount account) 
    AuthCredential credential = 
GoogleAuthProvider.getCredential(account.getIdToken(), null);
    firebaseauth.signInWithCredential(credential)
            .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
                        Log.d("TAG", "signInWithCredential:success");
                        FirebaseUser user = firebaseauth.getCurrentUser();
                       // updateUI(user);
                     else 
                        // If sign in fails, display a message to the user.
                        Log.w("TAG", "signInWithCredential:failure", 
 task.getException());
                        Toast.makeText(googleact.this, "Authentication 
failed.",
                                Toast.LENGTH_SHORT).show();
                       // updateUI(null);
                    

                    // ...
                
            );

    

下面是logcat 07-02 13:55:11.367 24547-24547/?我/艺术:不延迟启用 -Xcheck:jni (已经开启) 07-02 13:55:11.367 24547-24547/? W/art:X86 的意外 CPU 变体使用 默认值:x86 07-02 13:55:11.793 24547-24547/com.example.roomsarehere.foodishere 带系统: ClassLoader 引用了未知路径: /data/app/com.example.roomsarehere.foodishere-1/lib/x86 07-02 13:55:12.086 24547-24571/com.example.roomsarehere.foodishere I/DynamiteModule:考虑本地模块 com.google.android.gms.flags:2 和 远程模块 com.google.android.gms.flags:0 07-02 13:55:12.086 24547-24571/com.example.roomsarehere.foodishere I/DynamiteModule:com.google.android.gms.flags 的选定本地版本 07-02 13:55:12.131 24547-24571/com.example.roomsarehere.foodishere W/系统: ClassLoader 引用了未知路径: 07-02 13:55:12.136 24547-24571/com.example.roomsarehere.foodishere W/系统: ClassLoader 引用了未知路径:/system/priv- 应用程序/PrebuiltGmsCore/lib/x86 07-02 13:55:12.148 24547-24571/com.example.roomsarehere.foodishere D/ApplicationLoaders:忽略 Vulkan 层搜索路径 /system/priv- app/PrebuiltGmsCore/lib/x86:/system/fake-libs:/system/priv- app/PrebuiltGmsCore/PrebuiltGmsCore.apk!/lib/x86:/system/lib:/vendor/lib for 命名空间 0xa787a090 07-02 13:55:12.194 24547-24547/com.example.roomsarehere.foodishere I/FA: 应用程序 测量开始,版本:11020 07-02 13:55:12.195 24547-24547/com.example.roomsarehere.foodishere I/FA: 到 启用调试日志运行: adb shell setprop log.tag.FA VERBOSE 07-02 13:55:12.222 24547-24571/com.example.roomsarehere.foodishere W/DynamiteModule:本地模块描述符类 com.google.android.gms.crash 未找到。 07-02 13:55:12.265 24547-24547/com.example.roomsarehere.foodishere V/FA: 已启用收藏

【问题讨论】:

崩溃日志,好吗? 先生,应用程序在真实设备上崩溃,但在模拟器内显示 toast “身份验证失败”意味着任务未完成。 【参考方案1】:
GoogleSignInOptions gso = new 
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build();

将此部分写在 onCreate() 之外并运行代码并再次在 onCreate() 中重写相同的代码,注释前一个并运行它可能会完成这项工作,我遇到了同样的问题。

【讨论】:

【参考方案2】:
    在 Firebase 控制台中启用 googleSignIn

    Android Studio 中的LoginActivity.java -

    public class LoginActivity extends AppCompatActivity implements 
     GoogleApiClient.OnConnectionFailedListener
    
    @BindView(R.id.sign_in_button)
    SignInButton signInButton;
    
    private FirebaseAuth mFirebaseAuth;
    private GoogleApiClient googleApiClient;
    private static int RC_SIGN_IN = 1;
    private DatabaseReference databaseReference;
    
    private ProgressDialog progressDialog;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    
        mFirebaseAuth = FirebaseAuth.getInstance();
    
        databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
        progressDialog = new ProgressDialog(this);
    
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(
                R.string.default_web_client_id))
                .requestEmail()
                .build();
        googleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    
        signInButton.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
                startActivityForResult(signInIntent, RC_SIGN_IN);
            
        );
    
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == RC_SIGN_IN) 
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
    
            progressDialog.setMessage("Signing in...");
            progressDialog.show();
    
            if (result.isSuccess()) 
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
             else 
                progressDialog.dismiss();
                Log.e(LoginActivity.this.getClass().getSimpleName(), "Google Sign-In failed.");
            
        
    
    
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) 
        Log.d(LoginActivity.this.getClass().getSimpleName(), "firebaseAuthWithGooogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mFirebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() 
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) 
                Log.d(LoginActivity.this.getClass().getSimpleName(), "signInWithCredential:onComplete:" + task.isSuccessful());
    
                if (!task.isSuccessful()) 
                    Log.w(LoginActivity.this.getClass().getSimpleName(), "signInWithCredential", task.getException());
                    Toast.makeText(LoginActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                 else 
                    progressDialog.dismiss();
                    checkUserExist();
                
            
        );
    
    private void checkUserExist() 
    
        if(mFirebaseAuth.getCurrentUser() != null)
    
            final String user_id = mFirebaseAuth.getCurrentUser().getUid();
    
            databaseReference.addValueEventListener(new ValueEventListener() 
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) 
    
                    if(dataSnapshot.hasChild(user_id))
                        Intent signinIntent = new Intent(LoginActivity.this,SplashActivity.class);
                        signinIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(signinIntent);
                    
                    else
                        Intent setupAccountIntent = new Intent(LoginActivity.this,SetupAccountActivity.class);
                        setupAccountIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(setupAccountIntent);
                    
                
    
                @Override
                public void onCancelled(DatabaseError databaseError) 
    
                
            );
        
    
    
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) 
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_LONG).show();
    
    

因此,在此活动中,当用户单击 google 登录按钮时,它会在 firebase 控制台上进行身份验证并转到设置帐户,用户可以在其中设置他们的帐户,就像您可以获取用户示例个人资料图片等的详细信息一样. 检查用户是否设置了帐户,然后它将进入启动器屏幕的启动活动。 获取用户的数据并将其保存在“用户”节点的数据库中。

    SplashActivity.java - 启动器屏幕

    public class SplashActivity extends AppCompatActivity 
    
    @BindView(R.id.start)
    Button start;
    
    private FirebaseAuth mFirebaseAuth;
    private FirebaseUser mFirebaseUser;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private GoogleApiClient googleApiClient;
    
    private DatabaseReference userDatabaseReference;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
    
        mFirebaseAuth = FirebaseAuth.getInstance();
        mFirebaseUser = mFirebaseAuth.getCurrentUser();
        userDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
    
        mAuthListener = new FirebaseAuth.AuthStateListener() 
            @Override
            public void onAuthStateChanged(FirebaseAuth firebaseAuth) 
                if (mFirebaseUser == null) 
                    Intent loginIntent = new Intent(SplashActivity.this,LoginActivity.class);
                    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(loginIntent);
                
            
        ;
    
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Auth.GOOGLE_SIGN_IN_API , gso)
                .build();
    
        checkUserExist();
    
    
    private void checkUserExist() 
    
        if(mFirebaseAuth.getCurrentUser() != null)
            final String user_id = mFirebaseAuth.getCurrentUser().getUid();
            userDatabaseReference.addValueEventListener(new ValueEventListener() 
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) 
    
                    if(!dataSnapshot.hasChild(user_id))
                        Intent setupAccountIntent = new Intent(SplashActivity.this,SetupAccountActivity.class);
                        setupAccountIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(setupAccountIntent);
                    
                
    
                @Override
                public void onCancelled(DatabaseError databaseError) 
    
                
            );
        
    
    
    @Override
    public void onStart() 
        super.onStart();
        googleApiClient.connect();
        mFirebaseAuth.addAuthStateListener(mAuthListener);
    
    
    @Override
    public void onStop() 
        if (mAuthListener != null) 
            mFirebaseAuth.removeAuthStateListener(mAuthListener);
        
        googleApiClient.disconnect();
        super.onStop();
    
    
    @OnClick(R.id.start)
    public void onViewClicked() 
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
        finish();
    
    

由于这是我的启动器活动,当用户打开应用程序时,如果未通过身份验证,它将进入登录,如果未设置帐户,则转到帐户设置活动。

【讨论】:

看起来你在同一个类中做 2 项不同的工作(正如你在我提供的代码中看到的那样。1.LoginActivity 和其他是 SplashActivity,它是启动器活动)所以 LoginActivity 处理谷歌标志在按钮单击和启动器活动中检查是否验证然后继续否则打开 LoginActivity 建议在登录类和 MainActivity 中使用 google 按钮登录,用户在打开应用程序后会看到,检查用户是否通过身份验证,否则将用户发送到登录屏幕跨度> @wahdatkashmiri 希望this 帖子对你有帮助 先生实际上我已经按照谷歌文档编写了代码我不知道是什么问题

以上是关于谷歌登录验证失败的主要内容,如果未能解决你的问题,请参考以下文章

YouTube API 被 Google 破坏。 '谷歌身份验证失败。原因:NoLinkedYouTubeAccount'

Flutter:使用谷歌身份验证在 Firebase 存储中实施任何身份验证失败

谷歌的 Firebase UI 身份验证失败并显示消息(代码:10 消息:10)

Django,自定义身份验证登录。身份验证失败时如何显示错误消息?

Laravel 验证登录表单验证在密码确认中失败?

Ssh密码验证失败