【问题标题】:How to create Firebase token on server for use with unit tests?如何在服务器上创建 Firebase 令牌以用于单元测试?
【发布时间】:2017-06-18 18:21:07
【问题描述】:

我需要使用节点对 Firebase 用户进行身份验证,以便测试一些服务器端方法。对于每个受保护的请求,我使用以下方法验证 Firebase 令牌:

firebase.auth().verifyIdToken(firebaseAccessToken).then(function(decodedToken) {
    // forward request
})

所以在我的测试中,我使用 Firebase 数据库中的 uid 创建了一个令牌

firebase.auth().createCustomToken(uid).then(function(token) {
    //add to header for requests
})

后来我读到,自定义令牌没有通过 verifyIdToken 方法验证,只有客户端生成的。

我看过这个答案 - server side verification of tokens in firebase

所以我在初始化 json 中添加了 databaseAuthVariableOverride

firebase.initializeApp({
  credential: firebase.credential.cert(serviceAccount),
  databaseURL: [dbURL],
  databaseAuthVariableOverride: {
    uid: [uid]
  }
});

在我的测试中仍然得到输出

Error: expected 200 "OK", got 401 "Unauthorized"

还有 firebase 错误 -

Error: 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.

那么我如何使用我当前的设置来模拟用户呢?

【问题讨论】:

标签: node.js firebase mocha.js firebase-authentication chai


【解决方案1】:

您可以从您的自定义令牌生成一个 Firebase Id 令牌,然后使用它进行验证。例如:

const rp = require("request-promise");

// 'customToken' comes from FirebaseAdmin.auth().createCustomToken(uid)
function getIdTokenFromCustomToken(customToken) {
    const url = `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=${API_KEY}`;
    const data = {
        token: customToken,
        returnSecureToken: true
    };

    var options = {
        method: "POST",
        uri: url,
        body: data,
        json: true // Automatically stringifies the body to JSON
    };

    return rp(options)
        // idToken is the firebase id token that can be used with verifyIdToken
        .then(parsedBody => parsedBody.idToken) 
        .catch(function(err) {
            // POST failed...
        });
}

【讨论】:

    【解决方案2】:

    这是Python script for generating Firebase ID tokens (not custom tokens)。

    python firebase_token_generator.py <UID>
    

    可能有更简单的方法可以做到这一点,但您可以从 Node.js 调用 Python 脚本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 2017-10-30
      • 2011-09-03
      • 2019-05-15
      • 2021-03-28
      相关资源
      最近更新 更多