Search code examples
graphqlaws-amplifyaws-appsync

AWS amplify has Mutations working with Cognito User but not queries


I have setup a GraphQL schema using AWS Amplify.
Here is the schema:

type User @model @auth(rules: [
  { allow: owner}
]) {
  firstName: String!
  lastName: String!
  userId: String! @primaryKey
  phoneNumber: String
  email: String!
}

type Listing @model @searchable
  @auth(rules: [
    { allow: public, operations: [read] },
    { allow: owner, operations: [create, update, delete], ownerField: "userId" }
  ]) {
  id: ID!
  type: String!
  rentEstimate: Int!
  latt : Float!,
  long : Float!,
 category: String!
  description: String!
  images: [String]!
  userId: String!
}

The strange issue is that I have enabled Cognito User Pools as can be seen here

    "aws_appsync_region": "us-east-1",
    "aws_appsync_authenticationType": "AMAZON_COGNITO_USER_POOLS",

For some reason, I am able to add Listings, update and delete them using the logged in user in App Sync.
Yet, I am unable to run Queries. I can only run queries when I use the API key option is AppSync.
Here is a sample Query that returns the following error for a Logged in user.

Query:

query MyQuery {
  listListings(filter: {userId: {eq: "loggedin-username"}}) {
    nextToken
    items {
      category
      description
    }
  }
}
{
  "data": {
    "listListings": null
  },
  "errors": [
    {
      "path": [
        "listListings"
      ],
      "data": null,
      "errorType": "Unauthorized",
      "errorInfo": null,
      "locations": [
        {
          "line": 2,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "Not Authorized to access listListings on type Query"
    }
  ]
}

The same works when I use the API_key in AppSync.

I have updated the api to reflect "AMAZON_COGNITO_USER_POOLS".


Solution

  • That is happening by design In the document it is stated:

    To grant everyone access, use the public authorization strategy. Behind the scenes, the API will be protected with an API Key.

    So in your schema, you need to give the owner read access to allow them to view the Listings, otherwise they can only be read via the API KEY.

    Change

    { allow: owner, operations: [create, update, delete], ownerField: "userId" }
    

    To

    //give the owner read access
    { allow: owner, operations: [create, update, delete, read], ownerField: "userId" }
    

    Amplify GraphQL uthorization-strategies