Home > Software engineering >  Middleware Firebase authentication clarification
Middleware Firebase authentication clarification

Time:04-01

I'm setting up my API routes with express and mongoose. Is this a secure way to do user authentication? Is there any way that the user could somehow inject another Firebase user.uid to get the token of an admin user (I'm using Firebase for auth)?

Backend:

myRoute.route('/sample/:id').delete((req, res, next) => {

  var user = req['currentUser'];

  UserModel.findById(user.uid, (error, data) => {
    if (error) {
      return next(error)
    } else {
      user = data;
      if (user.admin) {

        SampleModel.findByIdAndRemove(req.params.id, (error, data) => {
          if (error) {
            return next(error)
          } else {
            res.status(200).json({
              msg: data
            })
          }
        })

      } else {
        res.status(403).send('You are not authorised!');
      }
    }
  })
})
async function decodeIDToken(req, res, next) {
              if (req.headers?.authorization?.startsWith('Bearer ')) {

                const idToken = req.headers.authorization.split('Bearer ')[1];

                console.log(idToken);

                try {
                  const decodedToken = await admin.auth().verifyIdToken(idToken);
                  req['currentUser'] = decodedToken;
                } catch (err) {
                  console.log(err);
                }
              }

              next();
            }

Frontend:

const user = auth.currentUser;
const token = user && (await user.getIdToken());

      axios.delete(`${this.baseApiURL}/sample/${id}`, { headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      }
      }).then(() => {
        console.log("Done");
      })

CodePudding user response:

Is this a secure way to do user authentication?

Yes, just verifying the Firebase ID Token is enough.

Is there any way that the user could somehow inject another Firebase user.uid to get the token of an admin user

Creating a JWT is pretty straightforward but you'll need to know the exact signing key that Firebase uses to sign the token else verifyIdToken() will thrown an error.

  • Related