atkayla
atkayla

Reputation: 8839

How to get and pass the JWT through to server?

I am using React Native Firebase Auth, however my user profiles are actually stored in my relational database. Because of this, I have mapped the Firebase uid => PostgreSQL integer id. (Thinking of just using uid for everything to keep it simple instead of mapping to an id in my own db)?

Anyway, when my React Native app launches, my user is logged in through Firebase, and I get a response back with info like uid, refresh_token, etc.

How should I get and pass this user's token to my backend Node.js server to get their profile? It only seems like there is refresh_token from the auth response, which I shouldn't pass.

Currently, I am just passing the uid Firebase Auth gives to my backend server, assuming that's "secure enough" since they got it from logging in. Is this sufficient? I feel like I should pass some token -> decode it on the server -> get the uid?

If so, how to do this?

Upvotes: 0

Views: 812

Answers (1)

Salakar
Salakar

Reputation: 6304

You can use getIdToken() to retrieve the currently signed in users JWT. For example on your client:

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
}

Then, on your backend code via the admin sdk, retrieve the token header and verify the token and that the user exists, e.g. for the Node Admin SDK an ExpressJS middleware for this could look something like:

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();
};

For reference; the React Native Firebase docs for this method are here: https://rnfirebase.io/docs/v5.x.x/auth/reference/User#getIdToken

Upvotes: 2

Related Questions