我如何认证请求Firebase REST api获取已登录用户的Firebase项目列表?



我希望在我的网站上获取登录用户(不是我)的firebase项目列表。我似乎无法正确请求firebase rest api(端点),因为我收到401 UNAUTHENTICATED错误。

我遵循的步骤:

我在浏览器上使用firebase.auth().signInWithPopup对用户进行身份验证。以下是使用的作用域:

// 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);

然后我使用getIdToken方法从用户那里获得令牌。
const token = await auth.currentUser.getIdToken(true);

我使用这个令牌请求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());

但我总是得到401错误:

{
"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"
}
}

我做错了什么?

要获取用户的Firebase项目列表,您需要为项目的合作者用户提供OAuth2令牌。您正在尝试为Firebase身份验证用户使用ID令牌/JWT,这是不一样的。

按照文档生成访问令牌来获取可用于获取项目列表的值。

我刚刚找到了答案,firebase SDK确实给你一个带有idToken的accessToken。然后,你可以使用这个令牌来代替idToken来满足任何REST api的需求。

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);

最新更新