0
votes

I am creating a RESTful API for my firebase database using Cloud functions. All the tutorials and guides I found suggest using firebase-admin to get admin access to the database.

Here is my question: Is there a way to access the database the same way as the user would have directly? Like getting the auth token from the user and passing it on to the database to make changes the same way the user would. The security rules should prevent me if I try to make changes to a different user.

Possible solution: Access the database using the built-in REST API of the database and use ?auth=CREDENTIAL to authenticate the user. Is there an alternative using the firebase SDK?

1

1 Answers

0
votes

Is there a way to access the database the same way as the user would have directly?

Yes there is, I recommend you check out the sample here. But it requires that your code decodes and verifies the JWT of that user. The easiest way to do this is with the Admin SDK.

The sample uses the JavaScript SDK to get the token from the client:

firebase.auth().currentUser.getToken()

It passes this token to the server, which then verifies it using the Admin SDK:

admin.auth().verifyIdToken(idToken)

You can then create a second instance of the admin SDK and set this UID for your database requests:

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://databaseName.firebaseio.com",
  databaseAuthVariableOverride: {
    uid: "my-service-worker"
  }
});