-1

I'm getting an error when I make an API call using axios to create an API key. This is the second call. Before this call, I'm making another one to get a JWT. That call goes through without a problem and I'm able to receive the token. The problem occurs when I use the result/token from this call to create the API key

This is the error:

error: "Request failed with status code 401"

This is my code:

const createFpAPIKey = async (token) => {
    const raw = { name: "any name", type: "api" };
    const headers = {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
          };
    const url = "https://sandbox.fluidpay.com/api/user/apikey";
    let r = {};
    try {
      r = await axios({
        method: "post",
        url,
        data: raw,
        headers,
        withCredentials: true,
      });
      r = r.data;
      if (typeof r.body === "string") r = JSON.parse(r.body);
    } catch (e) {
      r = {
        errorType: "Error Fetching API",
        error: e.message,
      };
    }
    return r;
  },
Mustafa Yusuf
  • 132
  • 2
  • 13
  • Your code isn't valid JS. There should be an `=` after `const createFpAPIKey`. You also have a trailing `,` after the `headers` object. – Phil Nov 27 '22 at 22:22

1 Answers1

1

401 means unauthorized. Either the token is missing in the post request or your token is not valid or is not for the API you are trying to access.

You can also check on the network tab of your browser in chrome developer tools if the token is actually sent with your request or not.

If the token is sent correctly then I suggest you decode your jwt token at jwt.io to verify the validity.

I would suggest use axios as given below for post request.

var resp = await  axios.post(url, {
      data: ...
    }, {
      headers: {
        'Authorization': `Bearer ${token}` 
       } 
    })
iaq
  • 173
  • 1
  • 2
  • 10
  • It says `Invalid Signature`. Is the API incorrectly sending the token? – Mustafa Yusuf Dec 01 '22 at 20:31
  • There can be multiple reasons for not validating signature. First check that your IDP is running when you try to verify the jwt on Jwt.io and make sure you put the exact secret you used to encode the token in IDP. Also make sure that iss field matches the IDP url. – iaq Dec 02 '22 at 15:07
  • You can read more about invalid signature issue here https://stackoverflow.com/questions/50774780/always-getting-invalid-signature-in-jwt-io – iaq Dec 02 '22 at 15:08