React app with Cognito User pool: Not authorized to access API

0

I started with a new React project with AWS Amplify (using the Authenicator from the aws-amplify-react library), added an API and Auth with API Key and Cognito user pool. I'm able to log in with a user from my Cognito user pool and query and mutate my items in DynamoDB over the GraphQL API in the React client.

Until this point, everything was authorized by the API Key which should only allow read access for unauthenticated users. To restrict access to regsitered users, I added the following @Auth annotations in the model:

type Event @model 
  @auth(
    rules: [
      { allow: owner, operations: [create, update, delete], ownerField: "username" },
      { allow: public }
    ]
  )
  @key( 
...

When I now try to create a new item (an event in the my app), I get this error:
Not Authorized to access createEvent on type Mutation

Even though I'm logged in with a user from Cognito, the API is accessed with the API key. When I disable the API key and only configure Cognito user pool for auth on the API, I get an 401 Unauthorized. When calling the GraphQL mutations, my credentials are not provided. Also the owner field is not set. Did I miss something in my settings?

질문됨 4년 전3567회 조회
1개 답변
2

I found a solution by setting the following parameter on each request:

authMode: "AMAZON_COGNITO_USER_POOLS"

In retrospect, it seems logical to set the authMode on a query or mutation if you have multiple auth options configured. However, many tutorials and documentation only cover how to add authentication to the project and configure the @model with @auth. The fact that the auth mode has to be specified for every query or mutation is often not described in detail.

답변함 4년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠