如何从 Google oAuth 令牌中获取 Firebase ID 令牌

时间:2021-06-24 09:33:15

标签: node.js firebase flutter google-authentication

我正在构建一个执行 auth.SignInWithCredential({'accessToken'...,'idToken'...})

的 Flutter 应用程序

我希望应用程序执行后端请求,发送不记名令牌。 在后端,我需要使用 firebase 对该用户进行身份验证,并将 oAuth2 令牌用于 Google 服务,因为它是有范围的。

我没有这样做的聪明主意(除了在请求标头中发送 2 个令牌,这似乎有点矫枉过正)。

1 个答案:

答案 0 :(得分:0)

我的最终解决方案是仅将 Google 令牌发送到后端,并使用 signInWithIdp 生成 Firebase ID 令牌。这适用于任何服务器。

    const response = await fetch('https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=[firebase_web_key]', 
    { 'method': 'POST', 
    body: JSON.stringify({
      postBody: "access_token="+req.token+"&providerId=google.com",
      requestUri: "https://[firebase-project].firebaseapp.com",
      returnIdpCredential: true,
      returnSecureToken: true,
    }) })

    // contains idToken!
    const idpData = await response.json()

    res.locals.decodedIdToken = await admin.auth().verifyIdToken(idpData.idToken);
    ```