Vue3 + Firebase调用需认证的第二代Cloud Run函数(Firebase函数)时的403认证错误解决求助
我现在遇到了一个Vue3对接Firebase第二代Cloud Functions的认证问题,卡了好久,想请大家帮忙看看:
我的基础环境是Vue JS 3做前端,Firebase做后端,已经把Firebase作为依赖安装完成,具体情况如下:
我创建了Firebase应用处理后端逻辑,同时写了一个Firebase函数来接收Vue应用的REST API请求
这个函数的
package.json依赖如下:"dependencies": { "cors": "^2.8.5", "express": "^4.21.2", "firebase-admin": "^12.6.0", "firebase-functions": "^6.0.1" },函数目录下的
index.js代码是这样的:const {onRequest} = require("firebase-functions/v2/https"); const {getAuth} = require("firebase-admin/auth"); const express = require("express"); const app = express(); // 认证请求的中间件 app.use(async (req, res, next) => { const authHeader = req.headers.authorization || ""; const token = authHeader.split("Bearer ")[1]; if (!token) { return res.status(401).json({error: "Unauthorized"}); } try { const decodedToken = await getAuth().verifyIdToken(token); req.user = decodedToken; next(); } catch (error) { console.error("Error verifying token:", error); res.status(403).json({error: "Forbidden"}); } }); app.get("/hello", (req, res) => { res.json({message: "Hello, world!"}); }); // 将Express API暴露为单个Cloud Function exports.api = onRequest(app);这个函数名叫
api,本地测试完全正常,但部署后,函数URL是类似https://REGION-MY-APP-NAME.cloudfunctions.net/api的格式。前端Vue3里,我用Axios请求这个接口,同时用Firebase的方法生成token,代码如下:
const userCredential = await signInWithEmailAndPassword(auth, emailId.value, password.value); const token = await userCredential.user.getIdToken(); // 获取token
现在遇到的问题:
- 浏览器直接报CORS错误(我试过在函数代码里加CORS策略允许所有来源,但完全没用)
- 同时在Cloud Run函数的日志里看到这个错误:
"The request was not authenticated. Either allow unauthenticated invocations or set the proper Authorization header. Read more at [相关文档链接] Additional troubleshooting documentation can be found at: [相关文档链接]"
我试过把函数里的认证中间件代码删掉再部署,但还是报同样的错误。
因为公司政策限制,我不能开启函数设置里的“Allow unauthenticated invocations”选项。我知道可能是前端生成token的方式不对,也看到过Node.js生成对应token的方法,但我的场景只有Vue3前端,需要用这个第二代Firebase函数作为后端来处理Firestore的增删改查等任务,现在卡在这个403认证错误上了,有没有大佬能帮忙解决这个问题?
如果需要更多信息,我随时可以补充。
备注:内容来源于stack exchange,提问作者Tej Sanura

