Marko Jerkić

Learner's Deep Learning Blog

Firebase Authentication

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:

https://gist.github.com/markojerkic/63773b89fc781930a0e29cb673a954ae

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.

https://gist.github.com/markojerkic/241fdf48b754507a04393ce9f3e2ec7a

And the corresponding java file:

https://gist.github.com/markojerkic/f9a23f94e86ca41fbb12023ab17579dc

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.

https://gist.github.com/markojerkic/986a0b4b6bd606c37f0e2a8351d99145

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:

https://gist.github.com/markojerkic/df9ec2dd2c480966599e9dc02be62c93

Reference

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top