我想测试一个创建用户的云函数。
在正常情况下,我在浏览器中生成一个 idToken
并通过 header 将其发送到服务器:Authorization : Bearer etcIdToken
但是我想在没有浏览器的情况下测试这个功能。在我的摩卡测试中,我有:
before(done => {
firebase = require firebase.. -- this is suppose to be like the browser lib.
admin = require admin..
idToken = null;
uid = "AY8HrgYIeuQswolbLl53pjdJw8b2";
admin.auth()
.createCustomToken(uid) -- admin creates a customToken
.then(customToken => {
return firebase.auth() -- this is like browser code. customToken get's passed to the browser.
.signInWithCustomToken(customToken) -- browser signs in.
.then(signedInUser => firebase.auth() -- now i want to get an idToken. But this gives me an error.
.currentUser.getIdToken())
})
.then(idToken_ => {
idToken = idToken_
done();
})
.catch(err => done(err));
})
我得到的错误是:
firebase.auth(...).currentUser.getIdToken 不是函数
- getting the idToken like this works on client - and is documented here.
我直接尝试使用 signedInUser.getIdToken()
。同样的问题:
signedInUser.getIdToken 不是函数
- 未记录。只是一个测试。
我认为这是因为 firebase
对象不像我在这里做的那样供 node.js
使用。登录时 - 内容会保存在浏览器本地存储中 - 也许这就是原因。
但问题仍然存在。我如何在 node.js 中获取 idToken 以便能够进行测试:
return chai.request(myFunctions.manageUsers)
.post("/create")
.set("Authorization", "Bearer " + idToken) --- i need the idToken here - like would be if i'm getting it from the browser.
.send({
displayName: "jony",
email: "jony@gmail.com",
password: "123456"
})
我是不是处理错了?我知道,如果我可以获得 idToken
,它就会起作用。我需要浏览器吗?谢谢:)
最佳答案
来自 Exchange custom token for an ID and refresh token ,您可以使用 api 将自定义 token 转换为 id token 。因此,您只需首先从 uid 生成自定义 token ,然后将其转换为自定义 token 。这是我的示例:
const admin = require('firebase-admin');
const config = require('config');
const rp = require('request-promise');
module.exports.getIdToken = async uid => {
const customToken = await admin.auth().createCustomToken(uid)
const res = await rp({
url: `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=${config.get('firebase.apiKey')}`,
method: 'POST',
body: {
token: customToken,
returnSecureToken: true
},
json: true,
});
return res.idToken;
};
关于javascript - 在 firebase 中 - 如何在服务器上生成 idToken 以进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48268478/