AIo*_*Ion 9 javascript node.js firebase firebase-authentication google-cloud-functions
我想测试创建用户的云功能。
在正常情况下,在浏览器内部我生成一个,idToken并通过标头将其发送到服务器: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));
})
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
firebase.auth(...).currentUser.getIdToken is not a function- 像这样获取idToken可以在客户端上使用-并在此处进行了说明。
我直接尝试过signedInUser.getIdToken()。同样的问题:
signedInUser.getIdToken is not a function-未记录。只是测试。
我认为这是因为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"
})
Run Code Online (Sandbox Code Playgroud)
我要解决这个错误吗?我知道,如果我能得到,idToken它将起作用。我需要浏览器吗?谢谢 :)
L.迈耶的回答对我有用。
但是,rpnpm 包已被弃用并且不再使用。这是使用 axios 修改后的工作代码。
const axios = require('axios').default;
const admin = require('firebase-admin');
const FIREBASE_API_KEY = 'YOUR_API_KEY_FROM_FIREBASE_CONSOLE';
const createIdTokenfromCustomToken = async uid => {
try {
const customToken = await admin.auth().createCustomToken(uid);
const res = await axios({
url: `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=${FIREBASE_API_KEY}`,
method: 'post',
data: {
token: customToken,
returnSecureToken: true
},
json: true,
});
return res.data.idToken;
} catch (e) {
console.log(e);
}
}
Run Code Online (Sandbox Code Playgroud)
从Exchange自定义令牌获得ID和刷新令牌,您可以使用api将自定义令牌转换为id令牌。因此,您只需要首先从uid生成自定义标记,然后将其转换为自定义标记即可。这是我的样本:
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;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2056 次 |
| 最近记录: |