[英]Error 401 when trying to call Firestore database through API URL
I am attempting to fetch data from my Firestore Database through getServerSideProps
in my Next.js. The error I am getting is related to authentication (As a sidenote: I am using NextAuth for User authentication).我正在尝试通过我的 Next.js 中的
getServerSideProps
从我的 Firestore 数据库中获取数据。我得到的错误与身份验证有关(作为旁注:我正在使用 NextAuth 进行用户身份验证)。
When pasting the URL https://firestore.googleapis.com/v1/projects/PROJECT-ID/databases/products
in the browser, I get this:在浏览器中粘贴 URL
https://firestore.googleapis.com/v1/projects/PROJECT-ID/databases/products
时,我得到了这个:
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. 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",
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "CREDENTIALS_MISSING",
"domain": "googleapis.com",
"metadata": {
"service": "firestore.googleapis.com",
"method": "google.firestore.admin.v1.FirestoreAdmin.GetDatabase"
}
}
]
}
}
My getServerSideProps function looks like this:我的 getServerSideProps function 看起来像这样:
export async function getServerSideProps(context) {
const session = await getSession(context);
const products = await fetch("https://firestore.googleapis.com/v1/projects/PROJECT-ID/databases/products").then(
(res) => res.json()
);
return {
props: {
products,
session
},
};
}
The Firestore database has reading and writing permissions enabled. Firestore 数据库已启用读写权限。
The linked documentation in the error message is referring to the integration of Google Sign-In.错误消息中的链接文档指的是 Google 登录的集成。 Do I have to use Firebase Authentication to access the Firestore Database through the API URL?
我是否必须使用 Firebase 身份验证才能通过 API URL 访问 Firestore 数据库?
If you have permissions enabled, you need to pass an ID token to the REST API URL如果启用了权限,则需要将 ID 令牌传递给 REST API URL
Authorization: Bearer ${idToken}
You can get the idToken
from the client then save the token as a cookie.您可以从客户端获取
idToken
,然后将令牌保存为 cookie。
import { getAuth } from "firebase/auth"
//fetch token from a signed in user
const fetchToken= async () => {
const idToken = await getAuth().currentUser.getIdToken()
//save the token as a cookie
}
fetchToken()
In getServerSideProps, you can then get the token from the cookie and pass it to the REST API URL.在 getServerSideProps 中,您可以从 cookie 中获取令牌并将其传递给 REST API URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.