如何创建服务器单元测试使用火力地堡令牌?

问题描述 投票:5回答:2

我需要使用节点来验证用户火力地堡,所以我可以测试一些服务器端方法。对于每个受保护的要求,我使用验证令牌火力地堡:

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

所以在我的测试中,我创建了一个UID令牌从我的火力地堡数据库

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

后来我读了自定义的令牌不被verifyIdToken方法验证,只生成的客户端的。

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

因此,我增加databaseAuthVariableOverride给init JSON

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

仍然得到在我的测试输出

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

和火力点错误 -

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 firebase-authentication chai
2个回答
2
投票

这里有一个Python script for generating Firebase ID tokens (not custom tokens)

python firebase_token_generator.py <UID>

可能有更简单的方法来做到这一点,但你可以调用从节点的Python脚本。


0
投票

您可以生成自定义令牌的火力地堡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...
        });
}
© www.soinside.com 2019 - 2024. All rights reserved.