【问题标题】:How to get and pass the JWT through to server?如何获取 JWT 并将其传递给服务器?
【发布时间】:2019-03-06 19:27:33
【问题描述】:

我正在使用 React Native Firebase 身份验证,但我的用户配置文件实际上存储在我的关系数据库中。因此,我映射了 Firebase uid => PostgreSQL integer id。 (考虑只使用 uid 来保持简单,而不是映射到我自己的数据库中的 id)?

无论如何,当我的 React Native 应用程序启动时,我的用户通过 Firebase 登录,我收到回复,其中包含 uidrefresh_token 等信息。

我应该如何获取此用户的令牌并将其传递到我的后端 Node.js 服务器以获取他们的个人资料?似乎只有来自身份验证响应的refresh_token,我不应该通过。

目前,我只是将uid Firebase Auth 提供给我的后端服务器,假设这是“足够安全”,因为他们是通过登录获得的。这是否足够?我觉得我应该传递一些令牌 -> 在服务器上对其进行解码 -> 获取 uid?

如果是这样,该怎么做?

【问题讨论】:

    标签: firebase firebase-authentication react-native-firebase


    【解决方案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

    【讨论】:

    • 哇,非常感谢!我想firebase.auth().signInAndRetrieveDataWithEmailAndPassword() 会带着我需要的令牌回来,但我发现我需要调用一个单独的方法。
    猜你喜欢
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多