node.js - 如何解决 Nodejs google-auth-library 无效令牌签名错误?
问题描述
我正在为我的移动应用程序使用颤振。我尝试添加使用谷歌登录。Flutter 方面一切正常。我正在从移动应用程序获取 idToken 并发送到我的后端 nodejs。
现在,我想使用这个 idToken 在 nodejs 后端使用 google-auth-library 包验证用户的请求。
let token = "token"
const CLIENT_ID = "client_id"
const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
try {
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
// Or, if multiple clients access the backend:
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
});
const payload = ticket.getPayload();
const userid = payload['sub'];
console.log(payload)
} catch (error) {
console.log(error)
}
}
verify()
但是此代码总是返回此错误 => 错误:无效的令牌签名:在 OAuth2Client.verifySignedJwtWithCertsAsync (\node_modules\google-auth-library\build\src\auth\oauth2client.js:566:19)
我应该怎么做才能在nodejs后端验证这个idToken?
谢谢。
解决方案
如果您传递给函数的 idToken 来自您的 Flutter 应用程序的日志,那么由于 print()
.
我使用下面的代码片段打印出 idToken 并在 API 中使用它,这给了我一个成功的响应。
print('ID TOKEN');
String token = googleAuth.idToken;
while (token.length > 0) {
int initLength = (token.length >= 500 ? 500 : token.length);
print(token.substring(0, initLength));
int endLength = token.length;
token = token.substring(initLength, endLength);
}
推荐阅读
- linux - 如何从 jenkins 作业在工作区中创建点文件
- jquery - 仅将代码应用于索引
- android-studio - 无法在 android studio 中设置虚拟设备
- string - 快速全文搜索的数据结构
- python - Kafka-Python 使用自定义登录模块而不是 PlainLoginModule
- java - runtime.getruntime.exec 无法识别可执行文件
- r - R会话崩溃,当gbm()应用于因子响应变量时?请指教
- javascript - 如何在“如果条件”中传递布尔结果
- java - 如何模拟 object.getMap().get("String_Key_to_return_Object")
- python - 使用 PySpark 和以下教程的 Java 错误