Search code examples
reactjsamazon-web-servicesamazon-cognitoaws-appsync

AWS AppSync error 401 with userPool in React, but no error in AppSync console


I am getting a strange error, only when I try to run a query in my React app, but it works using the AppSync query console. The userPool is configured properly, and I am logged into the React app as the same user in my pool that works in the AppSync console.

I wrapped my entire App in withAuthenticator like this:

import aws_config from './aws-exports';
import Amplify, { API } from 'aws-amplify';
import { withAuthenticator } from '@aws-amplify/ui-react';
import { Auth } from '@aws-amplify/auth'
API.configure(aws_config);
Amplify.configure(aws_config);
Auth.configure(aws_config);
class App extends Component {
    ...
}
const AppWithAuth = withAuthenticator(App, true);
export default () => (
  <div className="auth-container">
    <AppWithAuth />
  </div>
);

The page I am trying to load runs a simple list query and I log to console for debugging. I also added an Auth check right beforehand the it looks like the auth is correct:

async componentDidMount() {
    console.log(await API.Auth.currentAuthenticatedUser())
    console.log(await API.graphql(graphqlOperation(listFacebookLogs, {limit: 10})))
}

My console output for the above is (with edits to remove identifying info):

CognitoUser {username: "james", pool: CognitoUserPool, Session: null, client: Client, signInUserSession: CognitoUserSession, …}
POST https://abcd1234.appsync-api.us-east-2.amazonaws.com/graphql 401

The response payload is: {"errors" : [ {"errorType" : "UnauthorizedException", "message" : "Permission denied" } ]}

Now if I log in as the same userPool used in my AppSync console, the query passes and I get my list returned to the query. This leads me to believe the auth is set up properly because the userPool login works in the AppSync console. So confirming that the withAuthenticator login prints just fine right before my query, should indicate I am authorized properly, right?

I have ensured my schema is set up properly with auth, my local amplify cli is synced, the aws-exports match the cloud, etc. Any help is greatly appreciated!

Passed query in AppSync query console: Passed Query

Failed query in browser via my React app: (you can see I print the correct authenticated user right before the query) Failed Query

The query: Query

My aws-exports used for auth: aws-exports

The schema: schema


Solution

  • Woot! Figured it out. When you create a Cognito Group, it creates a new IAM Role (worthless role). So what I had to do was go edit each Group and set the role to the Auth role that AppSync uses, not using the role it had created. I think alternatively, I can go into IAM and link the Group roles to the appsync moderated identities that I want. This would allow me to limit different groups to CRUD.