Firebase Authentication allows to add sign in and log in methods to your app. This Firebase Authentication is available on Android, iOS, Unity, Web and C++. As this is an Android development blog, we’re going to focus on how to implement Firebase Authentication to an Android app.
If you don’t already know how to implement the Firebase core SDK and create a Firebase project than check out this post.
Methods of Authentication
Firebase gives you a couple of methods of authentication. Most of you are just going to use the email and password but Firebase also enables you to use Facebook, Google, GitHub, Twitter, phone and anonymous.
You may remember that when we were messing around with Firebase Real Time Database, the Firebase Console had this tab called Rule. This tab contained a JSON tree which defined which users can read and write to the database. The default values that were in the file are “auth != null”. This rule allowed anyone with an authenticated account to both read and write to the database.
Firstly, you’re going to need to compile the Firebase Authentication SDK in your build.gradle file:
Setup the app design
I created a simple UI for this tutorial. The purpose of this UI is just to show you how Firebase Authentication works.
And the corresponding java file:
Set up the Firebase Console
Before we write any Firebase related code, first we need to enable these methods of authentication in the Firebase console. To do that, go to the console and click on Authentication in the side menu. Now click the SIGN-IN-METHOD tab. A list of available methods should appear. In this example, we’re going to implement email and password method.
Write the Java code
This following example has only one Activity. Preferably, you would have your Main Activity, and inside there, you would check if there is an authenticated user, and if not start the sign in activity. And I am going to show you how to do that at the end of the post.
Here, once the user is authenticated, we just make a Toast and clean the email and password fields. And id there isn’t an existing user with that email and password, that we create one.
Check is the user is authenticated
As I said before, preferably, you would have a separate sign in activity that shows up only if the user is not authenticated. You would do that like this: