skip to Main Content

I have an axios call using JWT token that works when I call the EC2 instance directly, but when I call it through the API Gateway, it returns:

success:    false
message:    "unauthorized access! no headers!"

here is the nodejs code:

exports.isAuth = async (req, res, next) => {
  if (req.headers && req.headers.authorization) {
    const token = req.headers.authorization.split(' ')[1];

    try {
      const decode = jwt.verify(token, process.env.JWT_SECRET);
      const user = await User.findById(decode.userId);
      if (!user) {
        return res.json({ success: false, message: 'unauthorized access!' });
      }

      req.user = user;
      next();
    } catch (error) {
      if (error.name === 'JsonWebTokenError') {
        return res.json({ success: false, message: 'unauthorized access!' });
      }
      if (error.name === 'TokenExpiredError') {
        return res.json({
          success: false,
          message: 'sesson expired try sign in!',
        });
      }

      res.res.json({ success: false, message: 'Internal server error!' });
    }
  } else {
    res.json({ success: false, message: 'unauthorized access! no headers!' });
  }
};

here is the Reactjs code:

const headers = {
   Accept: 'application/json',
   'Content-Type': 'multipart/form-data',
   authorization: `JWT ${token}`,
};

return axios.get(BE_URI + "/fetch-general-news", { headers });

I did however make sure the API Gateway’s endpoint allowed headers, but it looks like the headers are not being forwarded, what am I doing wrong? enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    Found it! thx for your help guys, so I'll leave the solution in case someone else gets blocked, you need to add the header you want AWS API Gateway to forward in the "Method Request" of your endpoint for it to be forwarded : enter image description hereenter image description here


  2. JWT Authorization is supported for HTTP API Gateway. For REST API, you need to use API Gateway Lambda Authorizer. Refer: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html

    Hope this will resolve your issue. Do report the outcome of your trial.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search