Using Firebase Authentication
We’re overhauling Dgraph’s docs to make them clearer and more approachable. If you notice any issues during this transition or have suggestions, please let us know.
In this step, we will add Firebase authentication per the sample Todo app with Firebase Authentication.
Create Project
Let’s start by going to the Firebase console and create a new project (Todo-app).
In the Authentication section, enable Email/Password
login. You can add a
custom domain to Authorized domains
below according to where you want to
deploy your app. By default localhost is added to the list.
Now we want to use the JWT that Firebase generates, but we also need to add custom claims to that token which will be used by our authorization rules.
To add custom claims to the JWT we need to host a cloud function which will
insert claims into the JWT on user creation. This is our cloud function which
inserts USER
: email
claim under the Namespace
https://dgraph.io/jwt/claims
.
Using the Firebase CLI
Clone the Todo Firebase app repo and try to deploy the function to the Firebase project created above.
- Install the Firebase CLI tool
npm install -g firebase-tools
. - Login into Firebase from the CLI
firebase login
. - Run
firebase init functions
then select an existing project (that you created above). - Select language as
JavaScript
for this example. - Replace
index.js
with the snippet above. - Deploy the function `firebase deploy —only functions.
Please refer to the deployment guide for more info.
Create Webapp
Create a web app from your Firebase project settings page.
After creating that, copy the config from there.
Setup your Firebase configuration and Dgraph Cloud
endpoint in the
config.json.
It looks like this:
Authentication with Firebase is done through the JWKURL
, where the JSON Web
Key sets are hosted by Firebase. Since Firebase shares the JWKs among multiple
tenants, you must provide your Firebase project-Id
to the Audience
field. So
the Dgraph.Authorization
header will look like this:
You don’t need to set the VerificationKey
and Algo
in the Authorization
header. Doing so will cause an error.
Update the schema, add the Authorization header (update the project-Id) -
Resubmit the updated schema to Dgraph or Dgraph Cloud.
React App
For an example of how to initialize the Firebase app with the updated
configuration (config
) settings, see
base.js.
To understand how the client gets the token and sends it along with each GraphQL
request, see
Auth.js.
We can see from the code that whenever there will be state
change,
currentUser
will be set to the new user
and context will return App
with
the new idToken
. App
will initialize the Apollo Client which will send this
idToken
in header along with every GraphQL request.
To review the Apollo Client setup, see App.js.
Now that we have a basic understanding of how to integrate Firebase authentication in our app, let’s see it in action!
Was this page helpful?