Home > database >  How to do authorization fetch with GraphQL POST request?
How to do authorization fetch with GraphQL POST request?

Time:12-13

I'm trying to make a GraphQL request by using fetch method to get a schema. On AWSAppSync in my settings I see the API URL and API ID, but I have no idea how to configure my fetch POST request properly to get the response with data I need.

Here is the code I'm trying to use:

fetch('https://qnwb7jaoxdyky6egh4.appsync-api.us-east-1.amazonaws.com/graphql', {
    method: 'POST',
    headers: { 
Authorization: 'Basic bnwak7alhw52rlioy',  <----- this is API ID from AWS AppSync settings
'Content-Type': 'application/json' 
},
    body: JSON.stringify({
      variables: {},
      query: `
      {
        __schema {
          types {
            kind
            name
            possibleTypes {
              name
            }
          }
        }
      }
    `,
    }),
  })
    .then((result) => result.json())
    .then((result) => {
      debugger;  <--------- here I'm expecting to see the response data, but I see an error "UnauthorizedException"

      // here we're filtering out any type information unrelated to unions or interfaces
      const filteredData = result.data.__schema.types.filter(
        (type) => type.possibleTypes !== null,
      );
      
      result.data.__schema.types = filteredData;
      fs.writeFile('./fragmentTypes.json', JSON.stringify(result.data), (err) => {
        if (err) {
          console.error('Error writing fragmentTypes file', err);
        } else {
          console.log('Fragment types successfully extracted!');
        }
      });
    });

I'm using API URL and API ID from AWS AppSync settings.

I don't know why, but I get an error: "message: "Unable to parse JWT token."

CodePudding user response:

I have passed the API key in headers like this, in my case, I am calling APPSync Graphql endpoint which works with API key

headers: {
        "x-api-key": "XXXX-XXXXXXX", // API key here
      },

CodePudding user response:

You need to pass the right headers in your AppSync POST request. The required headers vary by authorization mode. API Key auth is the default, check the AppSync console settings tab.

// API_KEY
headers: {
  `x-api-key`:  "da2-the.api.key.from.the.appsync.console"
}

// AMAZON COGNITO_USER_POOLS
headers: {
  Authorization: "ey.jwt.token.a.really.really.long.string.you.get.from.cognito.after.you.login",
  host: 'qnwb7jaoxdyky6egh4.appsync-api.us-east-1.amazonaws.com' // the middle bits of the URL
}
  • Related