Firebase: Google Sign-In Authentication FIREBASE

Firebase: Google Sign-In Authentication  

Firebase: Google Sign-In Authentication

Firebase: Google Sign-in Authentication

Google Sign-in Authentication. It is pretty easy to do.

Starting steps are the same as we have done with other authentication methods, which are as follows:

  1. Creating an Android project.
  2. Creating a Firebase project.
  3. Adding Firebase to the Android project or application, either manually or Firebase Assistance.
  4. Adding the required libraries and JSON files.

Step 1:

Apart from firebase auth and core libraries, we have to add google play services auth in app.gradle file

 

Step 2:

In the next step, we have to enable the Google sign-in method in Firebase console. We also have to add a project supporting email.

 

Step 3:

Just like our previous method, we have to set SHA-1 and SHA-256 keys.

 

 

 

Step 4:

In the next step, we will create the layout file that contains three buttons Google sign-in, sign-out, and sign-out and disconnect. The activity layout will look like:

 

Step 5:

Now, we will modify our MainActivity.java file to perform the Google sign-in authentication in the following way:

  1. //Implement OnClickListener for sign-in button   
  2. public class MainActivity extends AppCompatActivity implements View.OnClickListener {  
  3.    
  4.     //Adding tag for logging and RC_SIGN_IN for an activity result  
  5. private static final String TAG = "GoogleActivity";  
  6. private static final int RC_SIGN_IN = 9001;  
  7.    
  8.     // Adding Google sign-in client  
  9.     GoogleSignInClient mGoogleSignInClient;  
  10.    
  11.     //Creating member variable for FirebaseAuth  
  12. private FirebaseAuth mAuth;  
  13.    
  14.     @Override  
  15. protected void onCreate(Bundle savedInstanceState) {  
  16. super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.activity_main);  
  18.    
  19.         //Adding buttons to the OnClickListener  
  20.         findViewById(R.id.sign_in_button).setOnClickListener(this);  
  21.         findViewById(R.id.signOutButton).setOnClickListener(this);  
  22.         findViewById(R.id.disconnectButton).setOnClickListener(this);  
  23.    
  24.         //Building Google sign-in and sign-up option.  
  25. // Configuring Google Sign In  
  26. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
  27. // for the requestIdToken, use getString(R.string.default_web_client_id), this is in the values.xml file that  
  28.                 // is generated from your google-services.json file (data from your firebase project), uses the google-sign-in method  
  29.                 // web api key  
  30. .requestIdToken(getString(R.string.default_web_client_id))//Default_web_client_id will be matched with the   
  31.                 .requestEmail()  
  32.                 .build();  
  33.    
  34. // Build a GoogleSignInClient with the options specified by gso.  
  35. mGoogleSignInClient = GoogleSignIn.getClient(this, gso);  
  36.    
  37. // Set the dimensions of the sign-in button.  
  38. SignInButton signInButton = findViewById(R.id.sign_in_button);  
  39.         signInButton.setSize(SignInButton.SIZE_WIDE);  
  40.    
  41. // Initialize Firebase Auth  
  42. mAuth = FirebaseAuth.getInstance();  
  43.     }  
  44.      //Creating onStart() method.  
  45.     @Override  
  46. public void onStart() {  
  47. super.onStart();  
  48.    
  49. // Checking if the user is signed in (non-null) and update UI accordingly.  
  50. FirebaseUser currentUser = mAuth.getCurrentUser();  
  51.    
  52. if (currentUser != null) {  
  53.             Log.d(TAG, "Currently Signed in: " + currentUser.getEmail());  
  54.             Toast.makeText(MainActivity.this, "Currently Logged in: " + currentUser.getEmail(), Toast.LENGTH_LONG).show();  
  55.         }  
  56.     }  
  57.      //Calling onActivityResult to use the information about the sign-in user contains in the object.  
  58.     @Override  
  59. public void onActivityResult(int requestCode, int resultCode, Intent data) {  
  60. super.onActivityResult(requestCode, resultCode, data);  
  61.    
  62. // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);  
  63. if (requestCode == RC_SIGN_IN) {  
  64.             Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);  
  65. try {  
  66. // Google Sign In was successful, authenticate with Firebase  
  67. GoogleSignInAccount account = task.getResult(ApiException.class);  
  68.                 Toast.makeText(this, "Google Sign in Succeeded",  Toast.LENGTH_LONG).show();  
  69.                 firebaseAuthWithGoogle(account);  
  70.             } catch (ApiException e) {  
  71. // Google Sign In failed, update UI appropriately  
  72. Log.w(TAG, "Google sign in failed", e);  
  73.                 Toast.makeText(this, "Google Sign in Failed " + e,  Toast.LENGTH_LONG).show();  
  74.             }  
  75.         }  
  76.     }  
  77.     //Creating helper method FirebaseAuthWithGoogle().    
  78. private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {  
  79.         Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());  
  80.         //Calling get credential from the oogleAuthProviderG  
  81.         AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);  
  82. mAuth.signInWithCredential(credential)  
  83.                 .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {  
  84. //Override th onComplete() to see we are successful or not.   
  85.  @Override  
  86. public void onComplete(@NonNull Task<AuthResult> task) {  
  87. if (task.isSuccessful()) {  
  88. // Update UI with the sign-in user's information  
  89. FirebaseUser user = mAuth.getCurrentUser();  
  90.                             Log.d(TAG, "signInWithCredential:success: currentUser: " + user.getEmail());  
  91.                             Toast.makeText(MainActivity.this, "Firebase Authentication Succeeded ",  Toast.LENGTH_LONG).show();  
  92.                         } else {  
  93. // If sign-in fails to display a message to the user.  
  94. Log.w(TAG, "signInWithCredential:failure", task.getException());  
  95.                             Toast.makeText(MainActivity.this, "Firebase Authentication failed:" + task.getException(),  Toast.LENGTH_LONG).show();  
  96.                         }  
  97.                     }  
  98.                 });  
  99.     }  
  100.    
  101. public void signInToGoogle(){  
  102.         //Calling Intent and call startActivityForResult() method   
  103.         Intent signInIntent = mGoogleSignInClient.getSignInIntent();  
  104.         startActivityForResult(signInIntent, RC_SIGN_IN);  
  105.     }  
  106.    
  107. private void signOut() {  
  108. // Firebase sign out  
  109. FirebaseAuth.getInstance().signOut();  
  110.    
  111. // Google sign out  
  112. mGoogleSignInClient.signOut().addOnCompleteListener(this,  
  113. new OnCompleteListener<Void>() {  
  114.                     @Override  
  115. public void onComplete(@NonNull Task<Void> task) {  
  116. // Google Sign In failed, update UI appropriately  
  117. Toast.makeText(getApplicationContext(),"Signed out of google",Toast.LENGTH_SHORT).show();  
  118.                     }  
  119.                 });  
  120.     }  
  121.    
  122. private void revokeAccess() {  
  123. // Firebase sign out  
  124. FirebaseAuth.getInstance().signOut();  
  125.    
  126. // Google revoke access  
  127. mGoogleSignInClient.revokeAccess().addOnCompleteListener(this,  
  128. new OnCompleteListener<Void>() {  
  129.                     @Override  
  130. public void onComplete(@NonNull Task<Void> task) {  
  131. // Google Sign In failed, update UI appropriately  
  132. Log.w(TAG, "Revoked Access");  
  133.                     }  
  134.                 });  
  135.     }  
  136.    
  137.     @Override  
  138. public void onClick(View v) {  
  139. int i = v.getId();  
  140. if (i == R.id.sign_in_button) {  
  141. Adding signInToGoogle() method  
  142.  signInToGoogle();  
  143.         }  
  144. else if (i == R.id.signOutButton) {  
  145.             signOut();  
  146.         }  
  147. else if (i == R.id.disconnectButton) {  
  148.             revokeAccess();  
  149.         }  
  150.     }  
  151.    
  152.     @Override  
  153. public void onPointerCaptureChanged(boolean hasCapture) {  
  154.    
  155.     }  
  156. }  

#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries