I wish to fetch the list of firebase projects of a signed-in user (not me) on my website. I can't seem to request the firebase rest api correctly (endpoint) as I receive a 401 UNAUTHENTICATED error.
The steps I follow:
I am using firebase.auth().signInWithPopup on my browser to authenticate users. Here are the scopes used:
// Google provider
const provider = new GoogleAuthProvider();
// Additionnal scopes
provider.addScope("https://www.googleapis.com/auth/cloud-platform");
provider.addScope("https://www.googleapis.com/auth/firebase");
provider.addScope("https://www.googleapis.com/auth/datastore");
// Signin
signInWithPopup(auth, provider);
I am then using getIdToken method to get a token from the user.
const token = await auth.currentUser.getIdToken(true);
I use this token to request https://firebase.googleapis.com/v1beta1/projects:
const data = await window.fetch("https://firebase.googleapis.com/v1beta1/projects", {
headers: {
authorization: `Bearer ${token}`,
},
})
.then(res => res.json());
but I am always getting a 401 error:
{
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
What am I doing wrong?
To get a list of Firebase projects for a user you need an OAuth2 token for a user that is a collaborator on the projects. You are trying to use the ID token/JWT for a Firebase Authentication user, which is not the same.
Follow the documentation on generating an access token to get value that you can use to get a list of projects.
I just found the answer, the firebase SDK does give you an accessToken with the idToken. You can then use this token instead of the idToken for any of your REST api needs.
const result = await signInWithPopup(auth, provider);
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);