【发布时间】:2020-05-06 13:53:03
【问题描述】:
我使用 Google Endpoints 作为在 Google Run 容器服务中运行的 API 网关。 API 路径指向 Google 函数(节点 js)。对 API 网关的调用来自 Web 应用程序(即浏览器)。
其中一条路径是:/login,它使用 firebase.auth().signInWithEmailAndPassword 方法在 firebase 中对用户进行身份验证。我得到用户的令牌 ID 并将其在响应标头(身份验证承载)中发送回浏览器。这按预期工作。
当向端点发出其他请求(例如/check)时,令牌(在标头中)被包括在内。我想在处理任何请求之前使用 Firebase Admin 方法检查令牌的有效性。 Google Function 中为其中一个路由执行此操作的代码如下:
...
const decodeIdToken = async (req, res, next) => {
// Read the ID Token from the Authorization header.
const idToken = req.headers.authorization.split('Bearer ')[1];
try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken);
req.decodedToken = decodedIdToken;
next();
return;
} catch (error) {
return res.status(403).json({
status: 'failure',
data: null,
error: error.message
});
}
};
// use decodeIdToken as middleware
app.post('/check', decodeIdToken, (req, res, next) => {
return res.json({
status: 'success',
data: req.decodedToken,
error: null
});
});
当我通过直接调用 Google 函数触发器来调用(通过 Postman)路由时,两条路由都可以工作。但是,当我调用指向 Google 函数的 Google Endpoints 时,我在使用 Firebase Admin 对象时收到以下错误:
Firebase ID 令牌的“aud”(受众)声明不正确。应为 \"PROJECT-ID\",但得到的是 \"https://us-central1-PROJECT-ID.cloudfunctions.net/FUNCTION-NAME\"。确保 ID 令牌与用于验证此 SDK 的服务帐户来自同一个 Firebase 项目。有关如何检索 ID 令牌的详细信息,请参阅 https://firebase.google.com/docs/auth/admin/verify-id-tokens
在 NodeJs 中设置 Firebase Admin 对象时,我尝试了以下操作:
const admin = require('firebase-admin');
admin.initializeApp();
还有
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://PROJECT-ID.firebaseio.com"
});
【问题讨论】:
标签: node.js firebase-authentication google-cloud-functions firebase-admin google-cloud-endpoints-v2