In my project I use a bunch of GCP services, including Firestore, Cloud Functions and Firebase auth.
Taking the fact that users are able to login via Firebase auth service, I assume that it should be possible to check and authenticate users calling my cloud function. Issue is that I can not find any docs or example of how to do that.
I understand that there are special callable functions but it doesn't suit me. I am using express for handling requests.
Is it possible to retrieve some kind of JWT token from user logged in on client side (firebase auth) then send it with request to my cloud function and then check it somehow there? Or is there any other mechanism to achieve CF protection described above?
P.S. I saw this question, but it is not about what I am asking, because it is related to Firebase Functions and I am talking about Cloud Functions which is very similar but not exact same thing.
onRequest creates a standard API endpoint, and you'll use whatever methods your client-side code normally uses to make. HTTP requests to interact with them. onCall creates a callable. Once you get used to them, onCall is less effort to write, but you don't have all the flexibility you might be used to.
Securing access with identity. One way to control access to a function is to require that the requesting entity identify itself by using a credential. A credential is a "name" of some sort, secured by a secret that the entity knows or has access to, like a password or a hardware dongle.
You can use Firebase Authentication to allow users to sign in to your app using one or more sign-in methods, including email address and password sign-in, and federated identity providers such as Google Sign-in and Facebook Login.
You should use Cloud Functions for Firebase if you're a developer building a mobile app or mobile web app. Firebase gives mobile developers access to a complete range of fully managed mobile-centric services including analytics, authentication and Realtime Database.
So, according to Dougs suggestion and after some additional googling I found out the way which should work for me.
On client side we need to retrieve id token of authenticated user:
const token = await firebase.auth().currentUser.getIdToken(true);
Now we can actually add this token to any request we need. I am going to put in request headers while calling my HTTP triggered cloud function. For example:
...
const headers = {
'Authorization': token
}
const response = await fetch('CF_URL', {headers});
....
The last and most important thing here is to have verification logic on the serverside (Cloud functions in my case):
try {
const userData = await admin.auth().verifyIdToken(tokenFromHeaders);
console.log(userData.uid) // here we have uid of verified user
// check user access or do whatever we need here
} catch (e) {
// something go wrong
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With