Firebase Custom Authentication Using Cloud Functions

Abhimanyu
Make Apps Simple
Published in
2 min readMay 28, 2019
Source: https://cdn-images-1.medium.com/max/1200/1*zTdZMxbTkVdXCOoZlXLnsg.png

The main advantage of using Firebase Authentication is that we need not maintain any server or authentication system.

But to create an authentication system with username/password credentials, we are required to have a custom authentication system.

Using Cloud Functions, solves the problem of having a server or custom authentication system requirement.

Let’s see how to create a username/password authentication system in Firebase using cloud functions.

Create Firebase Project

  1. Create a new Firebase project in Firebase Console
  2. Create Firestore database in test mode

Android App Part

  1. Create a new project in Android Studio — “Username Password Auth”

2. Connect your Android App to the Firebase Project

3. Add Firebase Authentication and Firestore dependencies

Add UI for Authentication

Add 3 fragments for sign in, sign up and home.

Sign In Fragment:

2 EditText for username and password.

A button to sign in.

A button to switch to sign up fragment.

Sign Up Fragment:

2 EditText for username and password.

A button to create new account and sign in.

A button to switch to sign in fragment.

Home Fragment:

A TextView for Welcome message.

A button for sign out.

Authentication Code:

Firebase Server

  1. Initialize Firebase project in your local environment.
  2. Add the server code for authentication.
  3. In ts.config file, change strict to false.
  4. Deploy server code.

Server Code

Enable IAM

If you run the app in debugging mode with breakpoint on val response in authenticate on complete listener method, you can find a link to Enable IAM for that project.

To find the link, check in the debugger in the given location:

response -> 0 (status) -> value -> errorInfo -> value -> message -> value.

The message would be something link this:

“Identity and Access Management (IAM) API has not been used in project project_no before or it is disabled. Enable it by visiting required link to enable IAM then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.; Please refer to https://firebase.google.com/docs/auth/admin/create-custom-tokens for more details on how to use and troubleshoot this feature.”

  1. Open the link in a browser (make sure the google account associated with your project is used)
  2. Click on Enable button
  3. Open IAM and Admin
  4. Select google account and project
  5. In the list of Members, a member end with @appspot.gserviceaccount.com. Edit it to add a new role “Service Account Token Creator”.

--

--