GraphQL with Amplify gives 401 Unauthorised for React App (Before and After Adding Auth with Cognito)

Viewed 508

I am trying with Amplify and trying to create my first react application, to just fetch simple Ride model.

I am always getting 401 unauthorised error on localhost and after hosting to S3.

errorType: "UnauthorizedException"
message: "You are not authorized to make this call."
1 Answers

@SlackGadget's solution was essentially correct.

The default expiration time of the AppSync API key is 7 day, meaning if you do not set this in your initial congif of your Amplify build or use a different type of authentication, then your API will expire after 7 days. If you deploy within this timeframe then a new key is generated, but there is no real warning without checking AppSync.

To check follow these steps:

  1. Go to AWS AppSync
  2. Click on the app in question
  3. Click Settings in the side nav
  4. Check the key against what appears in your aws-exports.js file, if it has expired this will be the issue.

Solution:

  1. To initially fix it, re-deploy you app from the Amplify console to get it up and running an prevent the 401 error
  2. Then update the API locally, go to your <project-root>/amplify/backend/api/<api-name>/parameters.json file and add a APIKeyExpirationEpoch key. This take an expiration time in seconds of the key. You can then deploy this and the new key will have a new expiration date.
  3. You can also update the expiration key in the AppSync setting

Here are the docs for overwriting the Amplify parameters: https://docs.amplify.aws/cli-legacy/graphql-transformer/resolvers/#custom-resolvers

Related