簡體   English   中英

如何解決 Nodejs google-auth-library 無效令牌簽名錯誤?

[英]How to resolve Nodejs google-auth-library invalid token signature error?

我正在為我的移動應用程序使用 flutter。 我嘗試添加使用谷歌登錄。 Flutter 方面一切正常。 我正在從移動應用程序獲取 idToken 並發送到我的后端 nodejs。

現在,我想使用這個 idToken 在 nodejs 后端使用 google-auth-library package 驗證用戶的請求。

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?

謝謝。

如果您傳遞給 function 的 idToken 來自您的 flutter 應用程序的日志,那么由於print()的限制,您可能沒有在日志中打印整個 idToken。

我使用下面的代碼片段打印出 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM