How to implement Login and signup with Firebase Authentication in android studio.

In this blog, we will be learning how to login and authenticate in our Android application but with the help of Firebase. 

 Following is how the flow of this blog looks like:

·         Introduction to Firebase

·         Login and Authentication in Firebase

·         Example - Email login and registration

·         Closing notes

 Introduction to Firebase


 Firebase was developed in 2011 to create and provide support for mobile and web applications.Later on, in 2014, it was acquired by Google. It gives you a number of facilities that can be used for the fast development of your applications. So, all you need to do is build applications fastly without thinking of managing infrastructure.

Following are the products of Firebase that can be used in any applications:

  • Cloud Firestore: It is a NoSQL database that is used to easily store, sync, and query data for applications.
  • ML Kit: It gives the power of Machine Learning to your applications.
  • Authentication: It is used to authenticate the users of your applications.
  • Realtime Database: It is used to store and retrieve data in realtime.
  • Test Labs: It will test your applications on the devices hosted by Google.
  • Crashlytics: It provides you with the crash reports of your application.
  • Performance Monitoring: Monitors the performance of your application at each and every second.
  • In-App Messaging: It helps you to send in-app messages that helps your users to interact with you.
  • Google Analytics: It will generate a report of your application. For example, a report of users increased in the last one month or active users, etc.
  • Remote Config: It helps you to change or add some feature in your app even without putting any update.

Apart from the above-mentioned products of Firebase, some of the other Firebase products are Cloud Functions, Hosting, Cloud Storage, App Distribution, Predictions, A/B Testing, Cloud Messaging and Dynamic Links.

 In this blog, we will learn about the authentication part of the Firebase.

Login and Authentication in Firebase

Firebase authentication is used to authenticate the users of applications in a very easy manner. Not only for the users but for the developers also, it provides a very easy flow for the authentication and login process that is present in almost every application. 

Firebase supports authentication using email and password, phone numbers or even you can use facebook, google, twitter, github, etc.

To authenticate your users, all you need to do is get the authentication credentials from the user and then pass this credential to the Firebase Authentication SDK. These credentials can be email-password or mobile number or any token from identity providers like facebook, google, twitter, github, etc. After passing the credentials, Firebase will verify the credentials and in return, you will get a response that tells you if the authentication is successful or not.

Now, let's see how we can use Firebase login or authentication in our application.

Example - Email login and registration


In this section of the blog, we will learn how to login and register using Email and Password with the help of Firebase. In this example, we will be having four activities i.e. one for Login, one for Registration, one for password reset and one will be our MainActivity. The following image will describe the flow of activities:


To use Firebase Authentication in our application, we need to connect our project i.e. the Android Studio project to Firebase. Following are the steps that are used to connect an Android project to Firebase:

 Step 1: Open Android Studio and create a new project or open an existing project.

Step 2: In Android Studio, login with your email. You can find the login button at the top right corner of the Android Studio. (Remember the email id that you have used here)


Step 3: Open the Firebase Website and login into it. (use the same email id as used in Android Studio for login)

Step 4: After login, click on the "Go To Console" button that is present of the upper right side of the website.



Step 5: Click on "Add Project". 


Step 6: Enter the required details of the project and click on submit.



Step 7: After creating a project, you will see the below image of your project dashboard.Here, all the services of Firebase are shown and you can use any of them.

Step 8: In this blog, we are interested in the authentication part, so click on the        "Authentication" button and then switch to "Sign-in method" tab.

Step 9: In our example, we will signin by email. So, click on the edit button next to the "Email/Password" option and you will see the below screen.

Step 10: Enable Email/Password signin and click on "Save". You are done with the Firebase website part.

Step 11: Come back to your project in Android Studio and click on Tools > Firebase > Authentication.

Step 12: We are almost done, now we have to add our project in Android Studio with the project that we have created in the Firebase. So, click on "Email and password authentication". Here, we are having two options i.e. "Connect to Firebase" and "Add Firebase Authentication to your app". Firstly, we have to connect our project to Firebase, so, click on "Connect to Firebase" button.

Step 13: A list of projects, associated with your email will be displayed and you have to select the project that you have created earlier on Firebase and then click on "Connect to Firebase".

Step 14: Now, your project on the Android Studio is connected with the one present on the Firebase. Lastly, we have to add some dependencies to our projects. So, click on "Add Firebase Authentication to your app". A dialog box will be opened. Click on "Accept Changes" and it will automatically add all the dependencies to your project.

Finally, we are done with all the steps that are required to connect our Android Studio project with Firebase for Authentication. Now, let's move on to the coding part.

 In this example, we will be having four activities:

1) MainActivity:This is the main activity of the application. The user will be redirected to this activity if the user is successfully logged in or have created a new account. In the MainActivity, we are having options for changing password and Logout.

2) LoginAcitivty: This activity is used to login the user into the application and after successful login, transfer the user to MainActivity. It contains two EditText for taking email and password from the user. Two buttons for Login and Signup(signup button will transfer the user to the SignupActivity) and one TextView that will transfer the user to the ForgotPasswordActivity.

3) SignupActivity: This activity is used to register the user into the application and after successful registration, transfer the user to the MainActivtiy. It contains two EditText for taking email and password from the user for registration. Two buttons for Signup and Login(login button will transfer the user to the LoginActivity).

4) ForgotPasswordActivity: This activity is used to send the forgot password link to the user to set a new password. The reset link will be sent to the user's email id.

Register a user with email and password :

To register a user with email and password, firstly, you have to declare an instance of FirebaseAuth.

Now, in the onCreate() method, initialize the FirebaseAuth instance.

    auth = FirebaseAuth.getInstance()

To signup a user with email and password, we can take the help of createUserWithEmailAndPassword() method. This method takes email and password as a parameter, validates them and then create a new user.

auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, OnCompleteListener{ task -> if(task.isSuccessful){ Toast.makeText(this, "Successfully Registered", Toast.LENGTH_LONG).show() val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() }else { Toast.makeText(this, "Registration Failed", Toast.LENGTH_LONG).show() } })

That's it. Your user will be registered and you can see the registered user on the Firebase website under the Authentication section and then in the Users tab. If you are trying to register with the same email more than once, then you will receive an error or in simple words your task is unsuccessful.


Login a user with email and password :

Now, we need to login the user by authenticating the email and password entered by the user.

Firstly, declare an instance of FirebaseAuth.

Now, in the onCreate() method, initialize the FirebaseAuth instance.

  auth = FirebaseAuth.getInstance();

 To signin a user with email and password, we have one method called signInWithEmailAndPassword(). This method takes email and password as a parameter, validates them and then signin a user in your application if the validation is successful.  


auth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, OnCompleteListener { task -> if(task.isSuccessful) { Toast.makeText(this, "Successfully Logged In", Toast.LENGTH_LONG).show() val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() }else { Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show() } })

Send the change password link to email :

Sometimes, the user forgot his/her password and in that case, your application should provide some way of password reset. Things become easier when you use Firebase. In Firebase, with the help of sendPasswordResetEmail() method, you can send the password reset link to the user and by clicking on that link, the user can set the newer password.

Firstly, create an instance of FirebaseAuth.

 Now, in the onCreate() method, initialize the FirebaseAuth instance.

auth = FirebaseAuth.getInstance()

After that, you can use the sendPasswordResetEmail() to send the reset email to the user. This method takes email as a parameter.

auth.sendPasswordResetEmail(email) .addOnCompleteListener(this, OnCompleteListener { task -> if (task.isSuccessful) { Toast.makeText(this, "Reset link sent to your email", Toast.LENGTH_LONG) .show() } else { Toast.makeText(this, "Unable to send reset mail", Toast.LENGTH_LONG) .show() } })

Check your email, you have received a reset link.

Check if a user is logged in or not :

To check if a user is logged in or not, we can use the getCurrentUser() method to get the status of a user.

if(auth.currentUser == null){ val intent = Intent(this, LoginActivity::class.java) startActivity(intent) finish() }else{ Toast.makeText(this, "Already logged in", Toast.LENGTH_LONG).show() }

In the above code, if the user is logged in, then a toast will be displayed and if a user is not logged in then the LoginActivtiy will be launched.

Screenshot of Applications :







Logout the user :

Now, we are done with the login, signup and reset the password. Our next aim is to logout the user if it is already logged in. To do so, we are having one method named signOut(). So, just use this method to signout a user.


FirebaseAuth.getInstance().signOut()

Closing notes :


In this blog, we learned how to use Firebase for login and authentication in our application. Firebase provides a number of methods for doing the authentication task in a very easier manner. So, to perform a login or authentication task, you need to use those methods only. We saw how we can use email and password to login into an application. 

The project used in this blog is just for example purpose. In general to have a better user experience and app performance, you should use the modularization concept. 

Hope you learned something new today.

Have a look at our Android tutorials.

Do share this blog  with your fellow developers to spread the knowledge. You can read more blogs on Android on our blogging website.

Happy Learning :)


--------------------------------------------------------------------------------------                        Share this blog to spread the knowledge


Comments

Popular posts from this blog

🔥 Java Exception and Error Handling

Understanding How OOP Concepts Work with Real-Life Examples

🌿⚙️ Spring Boot Simplified