A tutorial for using Firebase to add authentication and authorization to a realtime Hasura app
Tags: authentication, graphql, firebase, authorization
Published: 2019-12-03 11:57:21

---
title: A tutorial for using Firebase to add authentication and authorization to a realtime Hasura app
published: true
date: 2019-03-06 05:10:22 UTC
tags: authentication, graphql, firebase, authorization
canonical_url: https://blog.hasura.io/authentication-and-authorization-using-hasura-and-firebase/
---

![](https://blog.hasura.io/content/images/2019/03/rawpixel-783430-unsplash-1.jpg)<figcaption>Photo by <a href="https://unsplash.com/photos/qBinFqb_i0c?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">rawpixel</a> on <a href="https://unsplash.com/search/photos/keycard?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption>

_This tutorial was written by [Junyu Zhan](https://twitter.com/thezjy1) and published as part of the [Hasura Technical Writer Program](https://blog.hasura.io/the-hasura-technical-writer-program/) - an initiative that supports authors who write guides and tutorials for the open source Hasura GraphQL Engine._

## Introduction

Hasura helps you build production-level [3factor](https://3factor.app/) apps really fast. In addition to generating CRUD GraphQL APIs from your PostgreSQL database, it also provides ways to **authenticate** users using webhooks or JWT and helps you define granular access controls rules for your GraphQL schema (**authorization**). However, integrating an auth system with Hasura backend and some frontend still requires some effort, and can be tricky. This tutorial aims to demonstrate how to do that by making a real-time voting app like this [sample app](https://realtime-poll.demo.hasura.app/), but with auth built in. We are going to use Hasura for the backend, Firebase Authentication for authentication and React for the frontend.

It has mainly 3 steps:

1. Set up Hasura and create the data model using the Hasura Console.
2. Set up Authentication.
3. Build the React web app.

## Prerequisites

- React
- GraphQL
- Some SQL

## Try the demo

The demo is live at [hasura-vote.now.sh](https://hasura-vote.now.sh/), you can try it! It's a simple app in which you can vote for your favorite programming languages. The votes are updated in real time. After you sign in, you can also mark languages as "**loved**".

## Using Firebase Authentication versus building your own

Building a robust authentication system is no small effort. It's so important that it can make or break your app. Because the main focus of this tutorial is to **integrate** an auth system with Hasura and React, we are going to use the off-the-shelf Firebase Authentication. It's secure, offers many useful features such as third-party and passwordless sign-in and has a generous free tier.

## Step One: Hasura

It's very easy to get Hasura running. Just follow the [Deploy Hasura to Heroku Guide](https://docs.hasura.io/1.0/graphql/manual/getting-started/heroku-simple.html) and in the end, you will have a brand new instance running at a domain that looks like "**https://[your-heroku-project-name].herokuapp.com**".

![Image of Heroku Config Vars](https://github.com/thezjy/hasura-vote/raw/master/screenshots/heroku-config-vars.png?raw=true)

We need to set some environment variables as we are in the Heroku console.

Set `HASURA_GRAPHQL_ADMIN_SECRET` to some secret and write it down before you forget it, thus our API can't be accessed by some person on the Internet.

Since we will use JWT from Firebase, set `HASURA_GRAPHQL_JWT_SECRET` to `{"type":"RS512", "jwk_url": "https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com"}`.

Finally, set `HASURA_GRAPHQL_UNAUTHORIZED_ROLE` to `anonymous` because we do allow unauthenticated users to write and read some data.

Now it's time for data modeling. First, we need a " **programming\_language**" table with " **name**" and " **vote\_count**" field.

![Image of programming_language table](https://github.com/thezjy/hasura-vote/raw/master/screenshots/programming-language-table.png?raw=true)

Also, we need a " **loved\_language**" table to record whether a language is loved by some user. Since a user can only love a language once, we need to set the primary key as **name** and **user\_id** combined. There is no way to do that in the "Add Table" UI, but Hasura conveniently provides a way to execute raw SQL:

{% gist https://gist.github.com/shark-h/767708108d7e4e5f8a35009adeb5794e.js %}

![Image of loved_language table](https://github.com/thezjy/hasura-vote/raw/master/screenshots/love-language-table.png?raw=true)

After you create these two tables, Hasura will notice the one-to-many relationship between them and help you create the corresponding GraphQL relationship.

![Image of relationship](https://github.com/thezjy/hasura-vote/raw/master/screenshots/relationship.png?raw=true)

Hooray! Now that we have a data model, you can play with the API in GraphiQL. Insert some of your favorite languages. Give them some vote. Love them as a random "**user\_id**". Since we are signed in as admin, we can do anything we want. But we need to set proper permissions for the "**anonymous**" and "**user**" role. We allow both of them to select and update "**programming\_language**":

![Image of programming_language permission](https://github.com/thezjy/hasura-vote/raw/master/screenshots/programming-language-permission.png?raw=true)

For "**loved\_language**", we only allow the "**user**" role to insert, select and delete. Notice for insert the "**user\_id**" must come from "**X-Hasura-User-Id**".

![Image of loved_language permission](https://github.com/thezjy/hasura-vote/raw/master/screenshots/loved-language-permission.png?raw=true)

With permissions set, all we need is a secure way to get "**X-Hasura-User-Id**".

## Step Two: Firebase Auth

Go to the [Firebase website](https://firebase.google.com/) to create a new project. By default it's on the free plan, so don't worry about charges.

In the Authentication section of the Firebase console, turn on the Google sign-in provider. In this tutorial, we only use Google sign-in, but adding other providers is trivial. Notice at the bottom of the page, in "Authorized domains", `localhost` and a Firebase domain are automatically added. If you later decide to deploy the React app to another domain, you need to add it here for Google sign-in to work.

![Image of Firebase Authentication](https://github.com/thezjy/hasura-vote/raw/master/screenshots/firebase-authentication.png?raw=true)

Now we can sign in users and get their id token for Hasura in the React app, using the Firebase JS SDK. But for Hasura to know the identity of these users, whose data are stored in Firebase, we need to add some specific "custom claims" required by Hasura to the token. We will use Cloud Functions for Firebase to do that, following the [example](https://github.com/hasura/graphql-engine/tree/master/community/sample-apps/firebase-jwt) in the Hasura repo.

A cloud function is, well, some function that automatically runs "in response to events triggered by Firebase features and HTTPS requests". In our case the event is firebase user creation. When that happens, we'd like to add some extra data to the user's id token. The code is straightforward:

{% gist https://gist.github.com/shark-h/d1775b9c34c6b5156c4adf9e7b1d7a5a.js %}

The code with comments needs some more explanation. When a user signs in our React app, Firebase immediately gives us that user's data, including the id token we need to send to Hasura. But if it's the first time, in which the user is just created, the token may not include those custom claims. That's the reason we use Firebase real-time database to listen to a token refresh.

Deploying cloud function is simple. Follow the official [Get started guide](https://firebase.google.com/docs/functions/get-started), replace `index.js` with the code above and run `firebase deploy --only functions`. That's it.

Before you leave the Firebase console, you need to change one more setting. Go to the Realtime Database Rules section and change "read" from "false" to "true". Otherwise, the client won't be able to listen to the token refresh.

![Image of Realtime Database Rules](https://github.com/thezjy/hasura-vote/raw/master/screenshots/realtime-database-rules.png?raw=true)

## Step Three: React

Finally, it's time for us to build the exciting UI. We will use Apollo Client to query our GraphQL API. Follow the [client setup guide](https://www.apollographql.com/docs/react/advanced/subscriptions.html#subscriptions-client) to add all the needed npm packages.

Since the app is simple, we are only going to build two components: "Auth" and "App". "Auth" uses Firebase SDK to sign in users and pass that state to "App". "App" includes all the business logic: subscribing to the real-time data, voting and loving languages.

Auth:

{% gist https://gist.github.com/shark-h/43edcb6e6ccff9c4fe37b32f3a8363de.js %}

The code is straight forward if you are familiar with the new [Hooks API](https://reactjs.org/docs/hooks-intro.html). Notice how we use the Firebase realtime database to listen to the **refreshTime** which we set up in the Firebase cloud function. Also, we check whether a user's id token already contains custom claims to avoid useless refreshing.

App:

{% gist https://gist.github.com/shark-h/43d037fde6e43cbefb89cc7f7850dc8d.js %}

Notice how Hasura and GraphQL enable us to flexibly query data we need based on different auth state.

## Wrapping up

In this tutorial, we have built a real-time voting app with Hasura. We integrate a robust auth system both on the backend and frontend. You can see how Hasura makes tedious and hard jobs easy by providing a pluggable GraphQL and auth interface. Based on this model, there really is no limit on what kind of amazing apps you can build.

All the code in this tutorial are in the [Github repo](https://github.com/thezjy/hasura-vote).

## About the author 

Junyu Zhan is a full-stack web developer living in China. Right now he is building a cross-platform App with Flutter, React and Hasura. He loves taking long walks and swimming in his spare time. You can contact him at his email address (thezjy@gmail.com) or Twitter Account ([https://twitter.com/thezjy1](https://twitter.com/thezjy1)).