【发布时间】:2021-09-28 23:33:21
【问题描述】:
我是这里的新手,这是我的第一个问题。我正在使用 Typescript 和 Express 制作一个 API,该 API 连接到我的本地数据库,并希望使用 firebase 对用户进行身份验证。我阅读了他们文档上的说明,并认为我正在按照他们的要求设置服务帐户和管理 SDK。
当我在客户端和服务器端控制令牌时,我得到相同的令牌,但我不断收到此错误:
FirebaseAuthError: Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.
at FirebaseAuthError.FirebaseError [as constructor] (C:\coisas\nlw\node\node_modules\firebase-admin\lib\utils\error.js:44:28)
at FirebaseAuthError.PrefixedFirebaseError [as constructor] (C:\coisas\nlw\node\node_modules\firebase-admin\lib\utils\error.js:90:28)
at new FirebaseAuthError (C:\coisas\nlw\node\node_modules\firebase-admin\lib\utils\error.js:149:16)
at C:\coisas\nlw\node\node_modules\firebase-admin\lib\auth\token-verifier.js:138:23
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errorInfo: {
code: 'auth/argument-error',
message: 'Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'
},
codePrefix: 'auth'
这是我正在尝试做的客户端(Vue 应用程序的混合):
fetchPedidos: async function (parametros) {
return axios.get(parametros.endpoint, {
params: {
filter: parâmetros.filter || "",
page: parâmetros.page || 0,
size: parâmetros.size || 25,
sort: parâmetros.sort || "",
codCliente: parametros.codCliente || "",
codPedido: parametros.codPedido || "",
token: await firebase.auth().currentUser.getIdToken(true)
}
});
} (the then and catch are elsewere on the app)
这里是服务器端,express的中间件功能:
export async function firebase_auth(req: Request, res: Response, next: NextFunction) {
const token = JSON.stringify(req.query.token)
console.log(token);
try {
const _decodedToken = await admin.auth().verifyIdToken(token);
return next();
} catch (error) {
console.log(error);
return res.status(401).json({
mensagem: "Erro na autenticação do usuário",
erro: error
});
}
}
就像我之前说的,服务器端的 console.log 打印离开站点的相同令牌,但 admin sdk 抛出此错误,说它无法解码。我在这里做错了什么?
我看过一些类似的问题,但无法解决。
*编辑: console.log(req.query): Powershell print
至于解析器,我的 server.ts 中有这个:
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
*编辑2: 事实证明,我不应该为此使用 stringify,而只是指定我希望将令牌作为函数调用中的字符串。感谢@Dharmaraj 和@samthecodingman 为我澄清这一点!
【问题讨论】:
-
你遇到了什么错误?
-
对不起,忘记把错误打印在帖子里了,但我已经做了修改
-
你可以试试
const token = JSON.stringify(req.query.token)而不是const {token} = req.query,然后将它传递给verifyIdToken? -
然后我收到一个打字稿错误,说我无法将 Undefined 传递给 verifyIdToken()
-
这是字符串化,删除它,现在它可以工作了,感谢你和@Dharmaraj!
标签: node.js express firebase-authentication firebase-admin