我正在使用React Native Firebase Auth,但是我的用户配置文件实际上存储在我的关系数据库中。因此,我已经映射了Firebase uid => PostgreSQL整数ID。 (想到只对所有内容使用uid来保持简单,而不是映射到我自己的db中的id)?
无论如何,当我的React Native应用启动时,我的用户通过Firebase登录,并且我收到了诸如function mostNumbers(numbers) {
if (numbers !== undefined) {
var numArr = Array.prototype.slice.call(arguments);
var largest = numArr.reduce(function(previous, current) {
return (current > previous) ? current : previous;
})
var smallest = numArr.reduce(function(previous, current) {
return (current < previous) ? current : previous;
})
console.log(largest - smallest); //12.399999999999999
return largest - smallest; //12400
} else {
return 0;
}
}
console.log(Math.round(mostNumbers(10.2, -2.2, 0, 1.1, 0.50)*1000)); // Expected 12.4
//I've left off .toFixed(3) for the purpose of this example.
,uid
等信息的响应。
如何获取该用户的令牌并将其传递到后端Node.js服务器以获取其个人资料?看来auth响应中只有refresh_token
,我不应该通过。
当前,我只是将refresh_token
Firebase Auth传递给我的后端服务器,假设这是“足够安全的”,因为他们是从登录时获得的。这足够了吗?我觉得我应该传递一些令牌->在服务器上对其进行解码->获取uid?
如果是,该怎么做?
答案 0 :(得分:1)
您可以使用getIdToken()
来检索当前登录的用户JWT。例如在您的客户端上:
if (firebase.auth().currentUser) {
const token = await firebase.auth().currentUser.getIdToken();
// do something with token - e.g. send as a header with your api requests
}
然后,通过admin sdk在您的后端代码上,检索令牌标头并验证令牌和该用户是否存在,例如对于Node Admin SDK,用于此的ExpressJS中间件可能类似于:
module.exports = async function (req, res, next) {
const { token } = req.headers;
if (!token || !token.length) return next();
// validate JWT and pluck user id
const { uid } = await firebase.auth().verifyIdToken(token);
// find the user based on id
const user = await firebase.auth().getUser(uid);
if (user) {
// keep an instance of the User class on this request
req._user = user;
// raw serializable version of the user for request debugging?
req.user = user.toJSON();
}
// TODO if (!user) res.send('Unauthorised');
return next();
};
供参考;此方法的React Native Firebase文档在这里:https://rnfirebase.io/docs/v5.x.x/auth/reference/User#getIdToken