Home > Blockchain >  Passing custom JWT token to firestore for authentication using flutter
Passing custom JWT token to firestore for authentication using flutter

Time:12-27

I want to create a rule for my firestore database that will allow users to have access to it based on a custom JWT token that they pass up. My backend has been developed in .NET and I'm using firebase to add some extra 'live' functionality to it.

Each user gets a JWT token from the API when they sign in and I want to know how to pass that token up to firestore & create a rule that will allow users to have read/write access using it if the token is valid

The thing i'm struggling with is being able to pass up any information (except the body) to firestore. For example, where in this code would I put the JWT token to pass it up as a header to firebase & how in the firebase rule would I access this header and decode it

As you can see below my database currently has no authentication.

Code to post data:

void sendMessage({
    String message,
    String clientId,
    String ptId,
    bool isPt,
  }) async {
    try {
      final messagesDoc = _db
          .collection('pt-info')
          .doc(ptId)
          .collection('clients')
          .doc(clientId)
          .collection('messages');

      await messagesDoc.add({
        'message': message,
        'dateTime': DateTime.now(),
        'sentByPt': isPt
      });
    } catch (e) {
      print(e);
    }
  }

Firestore rules

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

What i'm going for (I dont know how to decode a JWT token here or pass one into here but this is essentially what i'm trying to do)

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if JWT.decode(CUSTOM_TOKEN).isValid()
    }
  }
}

CodePudding user response:

The only information available in Firestore security rules is:

  1. The path that the request acts on.
  2. The updated document data (for write requests).
  3. The auth token of the Firebase Authentication user making the request.

You can't pass custom information to Firestore security rules, outside of these options. If you want to pass additional information, it'll have to be in one of these places.

Most common is to pass the additional information in the Firebase Authentication token in the form of either a custom token (minted with an Admin SDK), or custom claims in an existing token. In either of those cases, the user will have to sign in to Firebase Authentication with the custom/customized token, at which point the information will become available in your security rules under request.auth.token.

  • Related