I have a node API which runs a middleware method to authenticate the bearer token. Here is the code:
// middleware mthd
export const validateHeaderBearerToken = (req, res) => {
if (!req.headers.authorization || req.headers.authorization.split(' ').length !== 2
|| req.headers.authorization.split(' ')[0].trim() !== authConstants.BEARER_HEADER) {
res.status(HttpStatus.FORBIDDEN)
.send({ message: authConstants.TOKEN_INVALID_ERROR });
throw new AuthenticationException(authConstants.NO_VALID_TOKEN_IN_HEADER_ERROR);
}
return req.headers.authorization.split(' ')[1].trim();
};
// controller
searchApiV1Controller.use('/search/', validateHeaderBearerToken, searchRouter);
// mainService
export const checkAuthentication = async (req, res, next) => {
const bearerToken = req.headers.authorization;
logger.info(`[${getCorrelationId(req)}] Authenticating the request`);
const token = validateHeaderBearerToken(bearerToken, res);
let application;
await checkAuthorize(....);
...
It throws AuthenticationException
and responds with a Forbidden(403) error when I run it localhost. But When I run it remotely it responds with 502 Bad Gateway. What may be the reason?
Update: Below is the CW logs of that API call
updated again. I guess it's happening because the middleware is called in an async method. When I remove the assync-await it works perfectly. So based on my code AuthenticationException is occuring before res.status.send. How can we avoid this?