java - 使用 Firebase 登录 Google
问题描述
我是 firebase 新手。我正在尝试将 google 登录添加到我的应用程序中,但我在完成此操作时遇到了一些问题
登录.java
package com.example.app100;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.internal.SignInButtonImpl;
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 Signin extends AppCompatActivity {
private static final int RC_SIGN_IN = 2 ;
private static final String TAG ="sign in" ;
private FirebaseAuth mAuth;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListener;
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signin);
SignInButton signInButton = findViewById(R.id.sign_in);
mAuth = FirebaseAuth.getInstance();
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null)
startActivity(new Intent(Signin.this , MainActivity.class));
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
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) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
startActivity(new Intent(Signin.this , MainActivity.class));
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.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 = mAuth.getCurrentUser();
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
//Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
错误:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.app100, PID: 15815
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { (has extras) }} to activity {com.example.app100/com.example.app100.Signin}: java.lang.IllegalArgumentException: Must specify an idToken or an accessToken.
at android.app.ActivityThread.deliverResults(ActivityThread.java:4461)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4503)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.IllegalArgumentException: Must specify an idToken or an accessToken.
at com.google.firebase.auth.GoogleAuthCredential.<init>(com.google.firebase:firebase-auth@@19.3.0:3)
at com.google.firebase.auth.GoogleAuthProvider.getCredential(com.google.firebase:firebase-auth@@19.3.0:2)
at com.example.app100.Signin.firebaseAuthWithGoogle(Signin.java:105)
at com.example.app100.Signin.onActivityResult(Signin.java:92)
at android.app.Activity.dispatchActivityResult(Activity.java:7598)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4454)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4503)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I/Process: Sending signal. PID: 15815 SIG: 9
我在 stackoverflow 上阅读了其他答案,并从 Variant: debug Config: debug in firebase console 更新了 SHA1。
有人可以指导我如何使用 google 登录解决这些错误
。
解决方案
您需要添加 IdToken 进行身份验证
替换这个
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
和
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
更进一步,这里是 firebase google 登录的官方文档:https ://firebase.google.com/docs/auth/android/google-signin
推荐阅读
- r - geom_text() 在 ggplot 中标记来自不同绘图的两个单独的点
- mysql - 优化分页查询
- python - PyMongo + Flask:如何用 jinja 渲染内容?
- python - Python从txt中提取列列表,然后删除重复项并在newlist中排序
- c# - 通过属性过滤字典
- swift - 如何检查CoreData是否为空?
- python - 如何在另一个文件夹中创建文件夹?- Python
- git - “'/home/upulie/Desktop' 的 git 存储库有太多的活动更改,只会启用部分 Git 功能”
- python - typed-ast 的构建轮子失败
- java - Rest tamplate 400 null - 错误请求