如何在 Firebase 身份验证中正确验证令牌

How to properly verify a token in Firebase Authentication

我有一个使用 Firebase 通过 Phone OTP 成功登录用户的 React Native 应用程序。 登录后返回以下数据:

{"additionalUserInfo": {"isNewUser": false, "profile": null, "providerId": "phone", "username": null}, "user": {"displayName": null, "email": null, "emailVerified": false, "isAnonymous": false, "metadata": [Object], "phoneNumber": "+123456644", "photoURL": null, "providerData": [Array], "providerId": "firebase", "refreshToken": "AFxQ4_reXvXb6-L_9SWC4SCHVqxl9Rv6zWDdC_BTXySuk-MOfbjrzc4WcrIwF7XqY0zkl-XT7eQtczt1jOg1HUDQ2-Nj6yDJWZRXOMuFKTn5Ddzj9mIz1Lxigmww0Lfo1-vmErUJ_-EX2JLMD7nqep6WhuOxOMtttXUaWy5XHIUgkgzN8fHJwS9sMV3Q0A8leTAkxURbp0zlw4-5SoRBu_a-EPHWsWAY-g", "tenantId": null, "uid": "Tx90EgWkSCf6M23KjsfH5Cf5vIv1"}}

从上面的数据可以看出uid是Tx90EgWkSCf6M23KjsfH5Cf5vIv1

为了测试Firebase的Auth的verifyIdToken函数,我使用了上面的uid并在方法中传递:

admin
    .auth()
    .verifyIdToken('Tx90EgWkSCf6M23KjsfH5Cf5vIv1')
    .then((decodedToken) => {
        console.log('decodedToken', decodedToken)
    })
    .catch((error) => {
        //Handle error
        console.log('error', error)
    })

然后我收到以下错误:

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'
}

如何解决这个问题?

verifyIdToken()将用户的ID Token作为参数,而不是UID。您在 DecodedIdToken 对象中获取用户的 UID。要在您的 React Native 应用程序中获取用户的 ID 令牌,请尝试以下操作:

const token = await firebase.auth().currentUser.getIdToken();

然后将此令牌传递到您的后端并进行验证。你一定不能通过 UID 检查用户身份。始终验证 ID 令牌。

来自documentation,

If your Firebase client app communicates with a custom backend server, you might need to identify the currently signed-in user on that server. To do so securely, after a successful sign-in, send the user's ID token to your server using HTTPS. Then, on the server, verify the integrity and authenticity of the ID token and retrieve the uid from it. You can use the uid transmitted in this way to securely identify the currently signed-in user on your server.

您可以阅读更多关于基于令牌的身份验证 here