Firebase(Google登录身份验证)

如前所述, Firebase提供了不同类型的身份验证方法。在上一节中, 我们学习了如何使用Firebase UI和Firebase SDK进行身份验证。在本部分中, 我们将学习另一种方法, 即Google登录身份验证。这很容易做到。
开始步骤与我们对其他身份验证方法所做的相同, 如下所示:

  1. 创建一个Android项目。
  2. 创建Firebase项目。
  3. 手动或通过Firebase协助将Firebase添加到Android项目或应用程序。
  4. 添加所需的库和JSON文件。
步骤1:
除了Firebase身份验证和核心库外, 我们还必须在app.gradle文件中添加Google Play服务身份验证
Firebase(Google登录身份验证)

文章图片
第2步:
下一步, 我们必须在Firebase控制台中启用Google登录方法。我们还必须添加一个项目支持电子邮件。
Firebase(Google登录身份验证)

文章图片
第三步:
就像我们以前的方法一样, 我们必须设置SHA-1和SHA-256密钥。
Firebase(Google登录身份验证)

文章图片
步骤4:
在下一步中, 我们将创建包含三个按钮的布局文件, 这些按钮分别是Google登录, 退出以及退出和断开连接。活动布局如下所示:
Firebase(Google登录身份验证)

文章图片
步骤5:
【Firebase(Google登录身份验证)】现在, 我们将修改MainActivity.java文件以通过以下方式执行Google登录身份验证:
//Implement OnClickListener for sign-in button public class MainActivity extends AppCompatActivity implements View.OnClickListener {//Adding tag for logging and RC_SIGN_IN for an activity resultprivate static final String TAG = "GoogleActivity"; private static final int RC_SIGN_IN = 9001; // Adding Google sign-in clientGoogleSignInClient mGoogleSignInClient; //Creating member variable for FirebaseAuthprivate FirebaseAuth mAuth; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Adding buttons to the OnClickListenerfindViewById(R.id.sign_in_button).setOnClickListener(this); findViewById(R.id.signOutButton).setOnClickListener(this); findViewById(R.id.disconnectButton).setOnClickListener(this); //Building Google sign-in and sign-up option.// Configuring Google Sign InGoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)// for the requestIdToken, use getString(R.string.default_web_client_id), this is in the values.xml file that// is generated from your google-services.json file (data from your firebase project), uses the google-sign-in method// web api key.requestIdToken(getString(R.string.default_web_client_id))//Default_web_client_id will be matched with the .requestEmail().build(); // Build a GoogleSignInClient with the options specified by gso.mGoogleSignInClient = GoogleSignIn.getClient(this, gso); // Set the dimensions of the sign-in button.SignInButton signInButton = findViewById(R.id.sign_in_button); signInButton.setSize(SignInButton.SIZE_WIDE); // Initialize Firebase AuthmAuth = FirebaseAuth.getInstance(); }//Creating onStart() method.@Overridepublic void onStart() {super.onStart(); // Checking if the user is signed in (non-null) and update UI accordingly.FirebaseUser currentUser = mAuth.getCurrentUser(); if (currentUser != null) {Log.d(TAG, "Currently Signed in: " + currentUser.getEmail()); Toast.makeText(MainActivity.this, "Currently Logged in: " + currentUser.getEmail(), Toast.LENGTH_LONG).show(); }}//Calling onActivityResult to use the information about the sign-in user contains in the object.@Overridepublic 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 FirebaseGoogleSignInAccount account = task.getResult(ApiException.class); Toast.makeText(this, "Google Sign in Succeeded", Toast.LENGTH_LONG).show(); firebaseAuthWithGoogle(account); } catch (ApiException e) {// Google Sign In failed, update UI appropriatelyLog.w(TAG, "Google sign in failed", e); Toast.makeText(this, "Google Sign in Failed " + e, Toast.LENGTH_LONG).show(); }}}//Creating helper method FirebaseAuthWithGoogle().private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); //Calling get credential from the oogleAuthProviderGAuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener< AuthResult> () {//Override th onComplete() to see we are successful or not. @Overridepublic void onComplete(@NonNull Task< AuthResult> task) {if (task.isSuccessful()) {// Update UI with the sign-in user's informationFirebaseUser user = mAuth.getCurrentUser(); Log.d(TAG, "signInWithCredential:success: currentUser: " + user.getEmail()); Toast.makeText(MainActivity.this, "Firebase Authentication Succeeded ", Toast.LENGTH_LONG).show(); } else {// If sign-in fails to display a message to the user.Log.w(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(MainActivity.this, "Firebase Authentication failed:" + task.getException(), Toast.LENGTH_LONG).show(); }}}); }public void signInToGoogle(){//Calling Intent and call startActivityForResult() method Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); }private void signOut() {// Firebase sign outFirebaseAuth.getInstance().signOut(); // Google sign outmGoogleSignInClient.signOut().addOnCompleteListener(this, new OnCompleteListener< Void> () {@Overridepublic void onComplete(@NonNull Task< Void> task) {// Google Sign In failed, update UI appropriatelyToast.makeText(getApplicationContext(), "Signed out of google", Toast.LENGTH_SHORT).show(); }}); }private void revokeAccess() {// Firebase sign outFirebaseAuth.getInstance().signOut(); // Google revoke accessmGoogleSignInClient.revokeAccess().addOnCompleteListener(this, new OnCompleteListener< Void> () {@Overridepublic void onComplete(@NonNull Task< Void> task) {// Google Sign In failed, update UI appropriatelyLog.w(TAG, "Revoked Access"); }}); }@Overridepublic void onClick(View v) {int i = v.getId(); if (i == R.id.sign_in_button) {Adding signInToGoogle() method signInToGoogle(); }else if (i == R.id.signOutButton) {signOut(); }else if (i == R.id.disconnectButton) {revokeAccess(); }}@Overridepublic void onPointerCaptureChanged(boolean hasCapture) {}}

Firebase(Google登录身份验证)

文章图片
Firebase(Google登录身份验证)

文章图片

    推荐阅读