Firebase JWT with Flutter

Welcome to dgraph…

You should not be able to specifically query your user database, as that is what rule you have. This SHOULD NOT work. If this does, it would be very interesting considering you do not have your headers implemented correctly.

I am NOT a flutter developer, but your header should not use Bearer, this is a hazura thing. Your header should be:

headers: {
  'X-Auth-Token': token
}

Here are a few examples I found:

And a typescript version maybe you can translate:

You also don’t need a callable function. You can just create the custom claim with a user onCreate function:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

admin.initializeApp();

exports.addUser = functions.auth
  .user()
  .onCreate((user: admin.auth.UserRecord) =>
    admin
      .auth()
      .setCustomUserClaims(user.uid, {
        "https://dgraph.io/jwt/claims": {
          "USER": user.email,
        }
      }).catch((e: string) => console.error(e))
  );

It will not be immediately avaiable on the front end when you create a user unless you refresh the claim (or re-login). You can do this in typescript like so:

  async getToken(): Promise<any> {
    return await new Promise((resolve: any, reject: any) =>
      this.afa.onAuthStateChanged((user: firebase.User | null) => {
        if (user) {
          user?.getIdTokenResult()
            .then(async (r: firebase.auth.IdTokenResult) => {
              const token = (r.claims["https://dgraph.io/jwt/claims"])
                ? r.token
                : await user.getIdToken(true);
              resolve(token);
            }, (e: any) => reject(e));
        }
      })
    );
  }

– Which basically says refresh the token manually only if the custom claim does not exist.

However, all this is extraneous as of 21.03.X since the email is already in the standard claim.

Hopefully, this will be on slash dgraph today so you don’t have to fool with firebase functions at all, @hardik?

Hopefully not too much longer regardless…

I hope this helps. I am just not a flutter developer. I can tell you that getToken() should be an async function which gets the token directly from firebase, not from localStorage like you find online in hazura examples. Firebase tokens are already stored in the localStorage and automatically update only when necessary.

J