Firebase Custom Authentication using REST API

MOhan Talupula
5 min readOct 9, 2019

--

In this article, we’ll see how to create custom authentication method using cloud_functions and REST API. I assume you have some background knowledge on What Firebase is ? and how to play with it.

This image is drawn by me. Looks Ugly? 😬 Sorry for that!

Firebase

Firebase is a back-end tool that lets you develop things in a most easy and effective way possible. As per Google Firebase is Google’s mobile platform that helps you quickly develop high-quality apps and grow your business. If you want to use basic authentication ( like email sign in and some auth providers) it is available here.

Get Started

I hope you need no introduction on how to install nodejs and npm.

  1. Install Firebase CLI.
npm i -g firebase-tools

2. Login to your Firebase on your machine

firebase login

3. On the root of your project folder, Initialize Firebase.

firebase init

4. Choose functions from the list.

Which Firebase CLI features do you want to set up for this folder? Press Space to select features, th 
en Enter to confirm your choices. (Press <space> to select, <a> to toggle all, <i> to invert selection)
❯◯ Database: Deploy Firebase Realtime Database Rules
◯ Firestore: Deploy rules and create indexes for Firestore
◯ Functions: Configure and deploy Cloud Functions
◯ Hosting: Configure and deploy Firebase Hosting sites
◯ Storage: Deploy Cloud Storage security rules
Firebase Project Init — Basic Setup

Yeah! We have completed our basic setup. Easy Right?

Now, we need to install additional dependencies in order to create our API.

npm i express cors

Now all that we have left to do is, to add some magical code to the index.js file in the functions directory. This is what your code looks like

const functions = require('firebase-functions'); 
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.yourFunction = functions.https.onRequest((req, res) => {});

Creating API

Now we are going to create an API that takes userId and password from request body and add it to database (realtime database or firestore).

Before adding data to database we need to make sure that there is no other user with same userId

  1. Import express and initialise it.
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());

Cors is used as Middleware.

2. export express app

exports.yourFunction = functions.https.onRequest(app);

3. Adding endpoint /register to our express app

app.post("/register", (request, response) => {})

There are many methods like get etc. You can choose accordingly.

4. Now we need to get userId and password from request.

app.post("/register", async (request, response) => {//getting fields from request body
const { userId, password } = request.body;
});

5. We need to make sure that there is no other user with same userId .So we will create a function that helps us to check whether the userId exists or not.

const isUserExists = async userId => {
const result = await db
.collection("users")
.where("userId", "==", userId)
.get();
return result.empty ? false : true;
};

This is the es6 way of writing a function. For more details about ES6, click here.

This functions takes userId as input and loops through firestore and find all the documents whose userId == userId .

6. Adding data to firebase

const userExists = await isUserExists(userId);if(userExists){
response.status(400).send({
"error" : "User already exists!"
});
}
else{
const addedUser = await admin.firestore().collection("users").add({
userId, // userId : userId
password // password : password
});
response.status(200).send({
"id" : addedUser.id,
userId,
});
}

You can also add try-catch to handle errors. At this stage this is what you end up with.

index.js

7. Now the intresting part is to test the API.

firebase serve

This will run the project on localhost . Basically, i use Postman to test the APIs.

API Testing

Deploy

Now we are done testing our API. The Final step is to deploy the API so that we can use across various devices.

firebase deploy

Errors

What? Facing any errors. Here’s the thing, sometimes we need credentials to access Database(like Firestore or Realtime Database).

  1. Go to Your Firebase Project and navigate to Project Settings on top.

2. Go to Service Accounts Tab and generate the private key.

3. Now import the file in your project and edit the code

const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccount");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});

4. I hope this will fix your problems. Even, if you face any errors after this step, you can DM me.

Conclusion

You can find the entire Github Repo here.

We can use this API in any front end applications and web apps. Feel free to experiment and explore.

We can also add more features like —

  1. Password Encryption
  2. Validation
  3. JWT for Protected Routes

We can be friends…
I hope this article helped you, we can connect on GitHub or Twitter and I would more than happy if you send your improvements, feedback, suggestions or ask queries.
Moreover, I love to make new friends and we can be friends, just drop me a text :)

--

--