Home > Blockchain >  How to implement partial JWT authentication on same API endpoint in NodeJS?
How to implement partial JWT authentication on same API endpoint in NodeJS?

Time:05-08

I have two GET request API like,

app.get('/fruits', async (req, res) => {
  let query = {}
  const cursor = fruitCollection.find(query)
  const fruits = await cursor.toArray()
  res.send(fruits)
})

app.get('/fruitsbyemail', verifyJWT, async (req, res) => {
  const decodedEmail = req.decoded.email
  const email = req.query.email.toLowerCase()
  if (decodedEmail === email) {
    const query = { email: email }
    const cursor = fruitCollection.find(query)
    const fruits = await cursor.toArray()
    res.send(fruits)
  } else {
    return res.status(403).send({ message: 'Forbidden Access' })
  }
})

How can I merge them into one API where, I will get the list of all fruits without authentication. But if I try to get the fruits by email, then JWT authentication will be needed.

I have tried this with checking empty query, where I will fetch all fruits if email is empty and I will fetch fruits by email if there email is present. But problem is that I have used a middle function "verifyJWT" at fruitsbyemail API. So when I am trying to merge them verifyJWT function is working and its returning 401/403. How can I solve this. Thank you.

CodePudding user response:

TBH I don't think it's good idea to merge public and private endpoints, but if business requirements justify it, then I would suggest to create new middleware which would cover this particular use case. Create new middleware, called i.e.: ConditionallyJwtVerification and put your logic there. Use the fact you have access to request in the middleware and verify JWT when needed (when email is present).

CodePudding user response:

You can do it in many ways, but it is always good to keep public and authenticated APIs separate.

app.get('/fruits', verifyJWT, async (req, res) => {
    const decodedEmail = req.decoded.email;
    const query = decodedEmail === req.query.email ? {email: req.query.email} : {};
    const cursor = fruitCollection.find(query)
    const fruits = await cursor.toArray()
    res.send(fruits);
  })

verifyJWT - You can check if the email exists else Forbidden Access for any request.

  • Related