Google Firebase Login Authentication Implementation In Android

Introduction

 
Firebase authentication provides,
  • Email and password-based authentication.
  • FirebaseUI (beta version).
Here, we will implement “Email and password-based authentication”, using Firebase in the Android Application. Firebase authentication uses bcrypt as a password hashing function.
 
For login authentication using Firebase, first of all, we will have to create an account in Firebase console.
  1. After creating an account, add Firebase to your Android project and download Google-services.json file.
     
    add firebase
     
    add firebase
     
  2. After adding the project place, download Google-Services.json into your Android app module root directory. Path : app/, otherwise Application will not connect with Firebase.
     
    Google-Services.json
     
  3. In build.gradle file of the project, add dependency: 
     
    classpath 'com.google.gms:google-services:3.0.0'.
     
    build.gradle
     
  4. In build.gradle file of the app, add dependency and add the plugin.
     
    compile "com.google.firebase:firebase-auth:9.0.2"
    apply plugin: 'com.google.gms.google-services'
     
    plugin
     
  5. Now, go to the Firebase console, select the Auth option from the left panel. Enable the Email/Password, a sign-in provider in Sign-In method.
     
    Sign-In method
     
  6. Get Firebase auth instance:
     
    private FirebaseAuth auth = FirebaseAuth.getInstance();
     
  7. For creating a new account as a new user, there is a method called:
    1. createUserWithEmailAndPassword(email, password)  
    2.   
    3. auth.createUserWithEmailAndPassword(email, password)  
    4.         .addOnCompleteListener(SignupActivity.thisnew OnCompleteListener<AuthResult>() {  
    5.             @Override  
    6.             public void onComplete(@NonNull Task<AuthResult> task) {  
    7.                 Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());  
    8.                 progressBar.setVisibility(View.GONE);  
    9.                 // If sign in fails, display a message to the user. If sign in succeeds  
    10.                 // the auth state listener will be notified and logic to handle the  
    11.                 // signed in user can be handled in the listener.  
    12.                 if (!task.isSuccessful()) {  
    13.                     Toast.makeText(SignupActivity.this"Authentication failed." + task.getException(),  
    14.                             Toast.LENGTH_SHORT).show();  
    15.                 } else {  
    16.                     startActivity(new Intent(SignupActivity.this, MainActivity.class));  
    17.                     finish();  
    18.                 }  
    19.             }  
    20.         });  
    output
     
  8. For authenticating the user, there is a method called: signInWithEmailAndPassword(email, password).
    1. auth.signInWithEmailAndPassword(email, password)  
    2.         .addOnCompleteListener(LoginActivity.thisnew OnCompleteListener<AuthResult>() {  
    3.             @Override  
    4.             public void onComplete(@NonNull Task<AuthResult> task) {  
    5.                 progressBar.setVisibility(View.GONE);  
    6.                 if (!task.isSuccessful()) {  
    7.                     if (password.length() < 6)  
    8.                     {  
    9.                         inputPassword.setError("Enter minimum 6 characters for password.");  
    10.                     }  
    11.                     else  
    12.                     {  
    13.                         Toast.makeText(LoginActivity.this"Check your email and password. Authentication failed.", Toast.LENGTH_LONG).show();  
    14.                     }  
    15.                 }  
    16.                 else  
    17.                 {  
    18.                     Intent intent = new Intent(LoginActivity.this, MainActivity.class);  
    19.                     startActivity(intent);  
    20.                     finish();  
    21.                 }  
    22.             }  
    23.         });  
    output
     
  9. Set up an AuthStateListener, that responds to the changes in the user's sign-in state:
    1. private FirebaseAuth.AuthStateListener authListener  
    2.  = new FirebaseAuth.AuthStateListener() {  
    3.     @Override  
    4.     public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {  
    5.         FirebaseUser user = firebaseAuth.getCurrentUser();  
    6.         //If user is not signed in getCurrentUser method returns null  
    7.         if (user != null) {  
    8.             // User is signed in  
    9.         }  
    10.         else {  
    11.             // User is signed out  
    12.             startActivity(new Intent(MainActivity.this, LoginActivity.class));  
    13.             finish();  
    14.         }  
    15.   
    16.     }  
    17. };  
    Note- AuthStateListener is added at the start of the activity and removed at the top of the activity.
    1. @Override  
    2. public void onStart() {  
    3.     super.onStart();  
    4.     auth.addAuthStateListener(authListener);  
    5. }  
    6.   
    7. @Override  
    8. public void onStop() {  
    9.     super.onStop();  
    10.     if (authListener != null) {  
    11.         auth.removeAuthStateListener(authListener);  
    12.     }  
    13. }  
    If the user is signed in, we can find the details of the current user:
     
    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
     
    for examples:
     
    • user.getEmail()
    • user.getToken()
    • user.getDisplayName()
    • user.getProviderId()
       
    After a successful login with Email id: [email protected],
    You can check the list of the users in Firebase console:
     
    console
     
    output
     
  10. In Firebase login authentication, there is also a functionality to send the password recovery instructions to the registered Email id.
     
    For this, there is a method called:
    1. sendPasswordResetEmail(emailId)   
    2.   
    3. auth.sendPasswordResetEmail(emailId)  
    4.         .addOnCompleteListener(new OnCompleteListener<Void>() {  
    5.             @Override  
    6.             public void onComplete(@NonNull Task<Void> task) {  
    7.                 if (task.isSuccessful()) {  
    8.                     Toast.makeText(PasswordResetActivity.this"Instructions have been sent to your registered email id", Toast.LENGTH_SHORT).show();  
    9.                 } else {  
    10.                     Toast.makeText(PasswordResetActivity.this"Sorry! Try Again.", Toast.LENGTH_SHORT).show();  
    11.                 }  
    12.                 progressBar.setVisibility(View.GONE);  
    13.             }  
    14.         });  
    output
     
    Password reset instructions to the registered Email id:
     
    instructions
     
    On clicking, reset the password link:
     
    reset password
     
    reset password
     
  11. For sign-out, there is a method called,
     
    signOut() 
    auth.signOut();


Similar Articles