DEV Community

loading...
Hasura

A tutorial for using Firebase to add authentication and authorization to a realtime Hasura app

hasurahq_staff profile image Hasura Originally published at blog.hasura.io on ・6 min read

Photo by rawpixel on Unsplash

This tutorial was written by Junyu Zhan and published as part of 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 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, 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, 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 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

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

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:

Image of loved_language table

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

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

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

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 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

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 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:

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, 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

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 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:

The code is straight forward if you are familiar with the new Hooks API. 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:

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.

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).

Discussion (1)

Collapse
ahmadsaleem profile image
Ahmad Saleem

Hi, it is so useful. but I have one issue, I can not get the anonymous token in server-side for the first load of the page, so I can not render the data on the server for the first load, any solution for that plz?

Thanks

Forem Open with the Forem app