Firebase Login and Authentication: Android Tutorial
Take out your Android Phones and try to count the number of applications that are not having any kind of login or authentication in it. So, you got it, right? There are very few applications that are not having any kind of login or authentication in it. In fact, when we start learning Android development, then most of us must have built the basic login and signup screen. So, are we going to build some login and signup screen here? No, but yes also ;) Don't worry, 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
- Pros and cons of using Firebase
- Closing notes
So, let's get started.
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.
- Crashlytics: It provides you with the crash reports of your application.
- Test Labs: It will test your applications on the devices hosted by Google.
- 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.
Note: By default, the authenticated users can read/write the data from the realtime database or cloud storage.
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 "(this is the second option that we found on step number 12). A dialog box will be opened. Click on " Accept Changes " and it will automatically add all the dependencies to your project.
Phew! 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.
As discussed earlier, in our example, we will be having four activities:
- 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.
- 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.
- 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).
- 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 .
private lateinit var auth: 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.
You can find the full code of activity_signup.xml from here and SignupActivity.kt from here .
Login a user with email and password
In the previous section, we saw how to register 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.
private lateinit var auth: 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. Following is the code for the same:
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()
}
})
You can find the full code of activity_login.xml from here and LoginActivity.kt from here .
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.
private lateinit var auth: 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 :)
You can find the full code of activity_forgot_password_activity.xml from here and ForgotPasswordActivity.kt from here .
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.
Update Password
You can update the password of a user by using the updatePassword() method. This method will take the new password as a parameter and will update the password for you.
So, create a FirebaseAuth instance and initialize the instance and after that use the updatePassword() method as below:
auth.currentUser?.updatePassword(password)
?.addOnCompleteListener(this, OnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Password changes successfully", Toast.LENGTH_LONG)
.show()
finish()
} else {
Toast.makeText(this, "password not changed", Toast.LENGTH_LONG)
.show()
}
})
Similarly, you can change the email by using the updateEmail() method in the same way as used in the case of updatePassword().
You can find the full code of activity_update_password.xml from here and UpdatePassword.kt from here .
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()
You can find the full code of activity_main.xml from here and MainActivity.kt from here .
Pros and cons of using Firebase
Some of the advantages of using Firebase are:
- Easy to integrate into our project.
- So many functions are available for performing complex operations.
- Realtime update.
- No configuration required on the server-side.
Some of the disadvantages of using Firebase are:
- The storage format is NoSQL. It uses JSON format.
- While performing authentication, you need to make sure that the user logged in the app should not have access to the database.
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. Other ways of login and authentication include a phone number, facebook, google, github, twitter, etc.
Note: 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. Read here .
Hope you learned something new today.
Have a look at our Android tutorials here .
Do share this blog with your fellow developers to spread the knowledge. You can read more blogs on Android on our blogging website .
Apply Now: MindOrks Android Online Course and Learn Advanced Android
Happy Learning :)
Team MindOrks!