Breaking News

Firebase Authentication with Android

Firebase Authentication with Android





Today we use Firebase Authentication with our app. We use a Google SignIn to authenticate with firebase. when any user Sign-In with google we get a Uid for that user and details of creation and last signed in of that user.

To create Firebase Authentication with Android. Follow the steps
  • Create a project in android studio and connect with firebase.
Connect to Firebase in Android
Connect to Firebase in Android


  • After connecting to Firebase, then do a code for Firebase Authentication.
In our FirebaseUi activity, we add a sign in with the google login button to authenticate a user with firebase.

firebaseui.xml
 <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   tools:context=".FireBaseUi"  
   >  
   <com.google.android.gms.common.SignInButton  
     android:id="@+id/sign_in_button"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_marginStart="8dp"  
     android:layout_marginTop="8dp"  
     android:layout_marginEnd="8dp"  
     android:layout_marginBottom="8dp"  
     app:layout_constraintBottom_toBottomOf="parent"  
     app:layout_constraintEnd_toEndOf="parent"  
     app:layout_constraintStart_toStartOf="parent"  
     app:layout_constraintTop_toTopOf="parent"  
     />  
 </androidx.constraintlayout.widget.ConstraintLayout>  

FirebaseUi.java
 package studio.harpreet.firebaseui;  
 import android.content.Intent;  
 import android.os.Bundle;  
 import android.util.Log;  
 import android.view.View;  
 import android.widget.Toast;  
 import androidx.annotation.NonNull;  
 import androidx.annotation.Nullable;  
 import androidx.appcompat.app.AppCompatActivity;  
 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.tasks.OnCompleteListener;  
 import com.google.android.gms.tasks.Task;  
 import com.google.firebase.FirebaseApp;  
 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 FireBaseUi extends AppCompatActivity {  
   private static final String TAG = "LoginActivity";  
   private static final int RC_SIGN_IN = 1001;  
   GoogleSignInClient googleSignInClient;  
   private FirebaseAuth firebaseAuth;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_fire_base_ui);  
     FirebaseApp.initializeApp(this);  
     SignInButton signInButton = findViewById(R.id.sign_in_button);  
     signInButton.setOnClickListener(new View.OnClickListener() {  
       @Override public void onClick(View view) {  
         // Launch Sign In  
         signInToGoogle();  
       }  
     });  
     // Configure Google Client  
     configureGoogleClient();  
   }  
   private void configureGoogleClient() {  
     // Configure Google Sign In  
     GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
         // for the requestIdToken, this is in the values.xml file that  
         // is generated from your google-services.json  
         .requestIdToken(getString(R.string.default_web_client_id))  
         .requestEmail()  
         .build();  
     // Build a GoogleSignInClient with the options specified by gso.  
     googleSignInClient = 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 Auth  
     firebaseAuth = FirebaseAuth.getInstance();  
   }  
   @Override  
   public void onStart() {  
     super.onStart();  
     // Check if user is signed in (non-null) and update UI accordingly.  
     FirebaseUser currentUser = firebaseAuth.getCurrentUser();  
     if (currentUser != null) {  
       Log.d(TAG, "Currently Signed in: " + currentUser.getEmail());  
       showToastMessage("Currently Logged in: " + currentUser.getEmail());  
     }  
   }  
   public void signInToGoogle() {  
     Intent signInIntent = googleSignInClient.getSignInIntent();  
     startActivityForResult(signInIntent, RC_SIGN_IN);  
   }  
   @Override  
   protected void onActivityResult(int requestCode, int resultCode, @Nullable 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);  
         showToastMessage("Google Sign in Succeeded");  
         firebaseAuthWithGoogle(account);  
       } catch (ApiException e) {  
         // Google Sign In failed, update UI appropriately  
         Log.w(TAG, "Google sign in failed", e);  
         showToastMessage("Google Sign in Failed " + e);  
       }  
     }  
   }  
   private void firebaseAuthWithGoogle(GoogleSignInAccount account) {  
     Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());  
     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  
               FirebaseUser user = firebaseAuth.getCurrentUser();  
               Log.d(TAG, "signInWithCredential:success: currentUser: " + user.getEmail());  
               showToastMessage("Firebase Authentication Succeeded ");  
               launchMainActivity(user);  
             } else {  
               // If sign in fails, display a message to the user.  
               Log.w(TAG, "signInWithCredential:failure", task.getException());  
               showToastMessage("Firebase Authentication failed:" + task.getException());  
             }  
           }  
         });  
   }  
   private void showToastMessage(String message) {  
     Toast.makeText(FireBaseUi.this, message, Toast.LENGTH_LONG).show();  
   }  
   private void launchMainActivity(FirebaseUser user) {  
     if (user != null) {  
       MainActivity.startActivity(this, user.getDisplayName());  
       finish();  
     }  
   }  
 }  

After Sign-In we will open MainActivity.

activity_main.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical"  
   tools:context=".MainActivity"  
   >  
   <TextView  
     android:id="@+id/textViewWelcome"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:layout_margin="32dp"  
     android:text="welcome"  
     android:gravity="center"  
     />  
   <Button  
     android:id="@+id/buttonLogout"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:gravity="center"  
     android:text="logout"  
     android:textAllCaps="false"  
     />  
 </LinearLayout>  
 
MainActivity.java
 package studio.harpreet.firebaseui;  
 import androidx.appcompat.app.AppCompatActivity;  
 import android.os.Bundle;  
 import android.content.Context;  
 import android.content.Intent;  
 import android.util.Log;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.TextView;  
 import androidx.annotation.NonNull;  
 import com.google.android.gms.auth.api.signin.GoogleSignIn;  
 import com.google.android.gms.auth.api.signin.GoogleSignInClient;  
 import com.google.android.gms.auth.api.signin.GoogleSignInOptions;  
 import com.google.android.gms.tasks.OnCompleteListener;  
 import com.google.android.gms.tasks.Task;  
 import com.google.firebase.auth.FirebaseAuth;  
 public class MainActivity extends AppCompatActivity {  
   private static final String TAG = "MainActivity";  
   private static final String USERNAME = "username";  
   Button logout;  
   TextView username;  
   public static void startActivity(Context context, String username) {  
     Intent intent = new Intent(context, MainActivity.class);  
     intent.putExtra(USERNAME, username);  
     context.startActivity(intent);  
   }  
   FirebaseAuth firebaseAuth;  
   GoogleSignInClient googleSignInClient;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     username = findViewById(R.id.textViewWelcome);  
     logout = findViewById(R.id.buttonLogout);  
     if (getIntent().hasExtra(USERNAME)) {  
       username.setText(String.format("Welcome - %s", getIntent().getStringExtra(USERNAME)));  
     }  
     logout.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         signOut();  
       }  
     });  
     googleSignInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_SIGN_IN);  
     firebaseAuth = FirebaseAuth.getInstance();  
   }  
   private void signOut() {  
     // Firebase sign out  
     firebaseAuth.signOut();  
     // Google sign out  
     googleSignInClient.signOut().addOnCompleteListener(this,  
         new OnCompleteListener<Void>() {  
           @Override  
           public void onComplete(@NonNull Task<Void> task) {  
             // Google Sign In failed, update UI appropriately  
             Log.w(TAG, "Signed out of google");  
           }  
         });  
   }  
 }  

Projects on Firebase Console
Projects on Firebase Console


  • Then open Authentication from the right menu.
Firebase Authentication in Firebase Console
Firebase Authentication in Firebase Console


  • Then under Sign-In method enable Google Sign-In.
Enable Google Sign-In with Firebase Authentication
Enable Google Sign-In with Firebase Authentication


OAuth Client Id on Google Developer console
OAuth Client Id on Google Developer console


  • Then Copy that client Id and paste it in your string.xml
strings.xml
 <string name="default_web_client_id">721******742-6s4q******qsmppom*******9516***m.apps.googleusercontent.com</string>  

  • Then run your app and sign in with your Google account and see the user and account id in the Users tab in authentication menu in Firebase Console.



Follow us for more posts like this, 
Subscribe Harpreet studio on Youtube  
Like Harpreet Studio on Facebook  
Follow me on Instagram 

No comments