Firebase Auth: How To Use Its REST API In 10 Minutes (2022)

Whatever app you use, you probably need to log in: auth―short for authentication and authorization―is everywhere. And if you want to develop an app, you can’t go around it.

Fortunately, we can count on a service like Firebase Auth and its REST API to save us days of work. At Rowy, we find the Google Firebase documentation a bit hard to navigate for first-time developers, so we are going to show you how to get started with Auth effectively and securely in the following article.

What's Firebase Auth

Firebase Auth is Google Firebase’s service responsible to provide authentication features to apps. Combined with Google Security Rules to handle authorization, it allows you to quickly get a user management system up and running.

In an app, authentication allows developers to know who is who, while authorization makes sure the users can do what he requests without messing someone else’s data up. For example, if we want to build a comment system, we need to be able to know who the person writing it is (with a username at least), and ensure you can only modify comments you wrote yourself.

Firebase Auth allows us to do that in a few lines of code in your favorite language, without having to take care of the server infrastructure or the database design.

Why Firebase Auth

First, Firebase Auth is easy to use. As you will see, you only need a couple lines to add user management features to your application. From scratch, the same features would take you days, if not weeks of work.

A proper auth system is key to avoid security threats. Say you don’t know how to encrypt passwords and your database leaks, you can possibly lose thousands of dollars in breach of trust and lawsuits. Having a ready-to-use solution like Firebase Auth that takes care of all the legalities and security fixes will give you the peace of mind you need to focus on what matters: your app’s value proposition.

Since Firebase Auth is built on top of the Google Cloud infrastructure, it is also highly scalable and you’ll never have to think about whether or not your server can handle a peak of traffic after your app goes viral.

Last but not least, it is completely free up to 50,000 monthly active users. In other words, you’ll be rich by the time you reach this threshold. Each additional 1000 users will only cost you an extra $5.5, maximum.

Untitled

How To Use Firebase Auth In Less Than 10 minutes

1. Connect to Firebase Auth

To use Firebase Auth, you need to create a Firebase project and enable Firebase Auth with email and password.

Firebase Auth allows you to pick from a variety of authentication strategies like email / password, but also using identity providers like Google, Apple, Facebook, Github, and so on. We base the following example on email-password authentication for the sake of simplicity.

Untitled

One way to get started fast without doing too much thinking is by using Rowy’s user management template. Rowy is a Firebase CMS that makes it easy and fast to get a working Firestore database up and running. By clicking Get Started, Rowy guides you step by step to save you from hours reading documentation:

https://demo.rowy.io/table/userManagement

You can then copy / paste the Firebase config found in your Firebase console in your Javascript project:

import { initializeApp } from "firebase/app"

import {
    getAuth
} from "firebase/auth";

const firebaseConfig = YOUR_FIREBASE_CONFIG_HERE
const app = initializeApp(firebaseConfig)
const auth = getAuth(app)

2. Signing up a user

You just need two things to sign up a user: an email and a password. Firebase takes care of storing the encrypted version of the password, validate the email, and send a verification email if you choose so―in only two lines of code!

import {
    createUserWithEmailAndPassword,
        sendEmailVerification
} from "firebase/auth";

const signup = async (email, password) => {
    await createUserWithEmailAndPassword(auth, email, password)
    await sendEmailVerification(auth.currentUser)
}

Once users register, you can either directly redirect them to the authenticated part of your app using the auth.currentUser variable containing all the user information you’ll need, or ask them to sign in.

3. Signing in a user

Whenever users leave your app, they will need to log in again. You just need to ask them for their email-password pair and Firebase will take care of populating the auth.currentUser variable again if the parameters are correct:

import {
    signInWithEmailAndPassword
} from "firebase/auth";

const signin = (email, password) => signInWithEmailAndPassword(auth, email, password)

4. Sign out a user

Signing out users after a short amount of time or upon request is a good practice to prevent people who can access the same machine from impersonating them:

import {
    signOut
} from "firebase/auth";

const signout = () => signOut(auth)

5. Reset password

Users will probably lose or forget their password at some point, so you’ll need to offer them a way to request a new one. Firebase Auth takes care of invalidating old passwords and sending password reset emails in a single line of code:

import {
    sendPasswordResetEmail
} from "firebase/auth";

const resetPassword = email => sendPasswordResetEmail(auth, email)

6. Call an authenticated API endpoint

Now, we want to be able to prevent unauthorized users from accessing other people’s data. For this tutorial, let’s use the example of a note system: anyone can write notes to themselves, but you should only be able to read your own notes.

To deal with authorization, you need to define additional Firebase Security Rules in your Firestore settings:

match /note/{noteId} {
        allow write: if request.auth != null;
        allow read: if request.auth.uid == resource.data.author;
}

The aforementioned security rule says that for the note collection, anyone can write notes as long as they are authenticated. But you’ll need to be the author of the note to be able to read it.

We can test it out with the following piece of code. First, we add a note containing the current user’s uid as the author, and then we ask Firestore to return all the notes that belong to the same users:

const db = getFirestore(app)

const user = auth.currentUser

await addDoc(collection(db, "note"), {
    name: "my first note",
    author: user.uid
})

await addDoc(collection(db, "note"), {
    name: "my second note",
    author: "another random uid"
})

const res = await getDocs(query(collection(db, "note"), where("author", "==", user.uid)))

res.forEach(s => console.log({
    id: s.id,
    ...s.data()
}))
// output: displays the note "my first note"

If you don’t add the where clause, Firestore will return a Permission Denied error because you aren’t authorized to access data that doesn’t belong to you.

Similarly, if the author’s uid is different from yours, it won’t be displayed.

Subscribe to Rowy

Great, we are now able to register new users, log them in and out, and handle common use cases like forgotten passwords or confirmation emails. We can even protect our API endpoints to make sure people can only access and manage their own data!

Now, you probably work with a team of people who will find valuable information from your user database. For example, a marketer could take all the registered emails and ask the users for their consent to send them a weekly newsletter. It’s a bit hard to do with Firebase without a developer, but with Rowy, you can quickly invite teammates to collaborate:

Screenshot 2022-11-25 at 13-39-27 Rowy - Low-code backend on Google Cloud and Firebase.png

Register today, it’s free and it only takes a few minutes to get going.

Get started with Rowy in minutes

Continue reading

Browse all