我目前正在开发一个项目,我必须允许我的 Firestore 数据库公开可用。我正在使用 firebase 与 firestore 进行通信。我尝试遵循一些文档,但我并没有真正理解它们。我指的是我见过的下面的链接...
为了更好地解释我的问题,我指的是 YouTube video这确切地证明了我的目标(尽管 swift 语言代码并不重要),但该教程并未按预期工作。本教程没有涵盖困扰我的身份验证部分。
我当前的问题是,当我点击时,我无法通过 firestore 进行身份验证
https://firestore.googleapis.com/v1/projects/my-project-id/databases?key=MY_PROJECT_KEY
当我使用 Postman 点击此 URL 时,我得到了这些结果。
{
"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"
}
}
我还尝试了其他几种使用 post 请求的方法,并将单个登录用户的 JWT token 作为 HTTP 正文中的 token 字段包含在内,但它们也响应为 401。
所以我正在尝试查找我需要提供的 API key 。
最佳答案
如 Firestore REST API documentation 中所述:
For authentication, the Cloud Firestore REST API accepts either a Firebase Authentication ID token or a Google Identity OAuth 2.0 token.
The token you provide affects your request's authorization:
Use Firebase ID tokens to authenticate requests from your application's users. For these requests, Cloud Firestore uses Cloud Firestore Security Rules to determine if a request is authorized.
Use a Google Identity OAuth 2.0 token and a service account to authenticate requests from your application, such as requests for database administration. For these requests, Cloud Firestore uses Identity and Access Management (IAM) to determine if a request is authorized.
该文档随后介绍了如何获取 Firebase ID token 或如何使用服务帐号生成访问 token 。您必须根据您的具体情况决定选择哪种方法(您仅通过 REST API 与 Firestore 交互吗?您是否将通过客户端 SDK 的调用(例如对 Firebase Auth 服务的调用)与对 API 的调用混合在一起?)。
After you obtain either a Firebase ID token or a Google Identity OAuth 2.0 token, pass it to the Cloud Firestore endpoints as an
Authorization
header set toBearer {YOUR_TOKEN}
.
下面是通过 JS SDK 获取 Firebase ID token ,然后构建 header 并通过 axios 库调用 Firestore API 端点( runQuery
用于查询集合)的示例:
const payloadObj = {
structuredQuery: {
where: {...},
orderBy: [
{
field: {
fieldPath: 'name',
},
direction: 'ASCENDING',
},
],
from: [
{
collectionId: '...',
},
],
limit: 200000,
},
};
const url =
'https://firestore.googleapis.com/v1/projects/<your-projecty>/databases/(default)/documents:runQuery';
firebase
.auth()
.signInWithEmailAndPassword('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c28392f281c3b313d3530723f3331" rel="noreferrer noopener nofollow">[email protected]</a>', '.....')
.then((userCredential) => {
return firebase
.auth()
.currentUser.getIdToken(/* forceRefresh */ true);
})
.then((token) => {
callHeaders = { Authorization: 'Bearer ' + token };
return axios({
url: url,
method: 'post',
headers: callHeaders,
data: payloadObj,
});
})
关于firebase - Firestore REST API |如何将 firestore Rest api 与 postman 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69493867/