How to restrict access to a url if it does not contain a particular header

Viewed 153

I'm implementing an API which would be called by different users, I want the user id to be to be provided via a header called "tenant" otherwise if not provided an error message should be thrown.

    if (! request.get('Tenant')) {
      return res.status(403).json({ error: 'No tenant header sent!' });
    }
    next();
  }, router);

I've tried the above code but it is not restricting access when the tenant header is not sent as part of the request.

1 Answers

Get the headers and look for the value in it

let headers = JSON.stringify(req.headers);

headers value will be like

    {
       "host":"localhost:8081",
       "connection":"keep-alive",
       "cache-control":"max-age=0",
       "accept-encoding":"gzip, deflate, sdch",
       "accept-language":"en-US,en;q=0.8,et;q=0.6"
   }


 for(let x in headers) {
      if(x['headers'] !== 'tenant'){
         return res.status(403).json({ error: 'No tenant information found!' });
      }else{
         res.redirect(301, '/otherEndpoint')
           or
         res.status(301).location('/otherEndpoint')
     }
   }

req.get('tenant'); will also work in express versions 4 and above

Or you could also use req.header('tenant') to check directly

Related