Amplify GraphQL Error not authorized to access create

Viewed 10070

In my app users have the ability to start a conversation with other users and after the conversation is created they can send messages to one another. However after trying to create a conversation between two users I get an error saying

 Failed to create graphql GraphQLResponseError<Conversation>: GraphQL service returned a successful response containing errors: [Amplify.GraphQLError(message: "Not Authorized to access createConversation on type Conversation", locations: Optional([Amplify.GraphQLError.Location(line: 2, column: 3)]), path: Optional([Amplify.JSONValue.string("createConversation")]), extensions: Optional(["data": Amplify.JSONValue.null, "errorType": Amplify.JSONValue.string("Unauthorized"), "errorInfo": Amplify.JSONValue.null]))]
Recovery suggestion: The list of `GraphQLError` contains service-specific messages 

This is my first time using GraphQL and it probably shows. I would like to give members of model Conversation the ability to create their convo. Can anyone possibly steer me in the right direction? The following is my GraphQL Schema

type User 
  @model 
  @auth(rules: [{ allow: owner, operations: [create, delete, update]}]) {
  id: ID!
  userSub: String!
  fullName: String!
  profileImageFileName: String!
  conversations: [ConvoLink] @connection(name: "UserLinks")
  messages: [ChatMessage] @connection(name: "UserMessages", keyField: "authorId")
  createdAt: String
  updatedAt: String
}

type Conversation
  @model
  @auth(rules: [{ allow: owner, ownerField: "members", operations: [create, delete, update] }]) {
  id: ID!
  messages: [ChatMessage] @connection(name: "ConvoMsgs", sortField: "createdAt")
  associated: [ConvoLink] @connection(name: "AssociatedLinks")
  name: String!
  members: [String!]!
  createdAt: String
  updatedAt: String
}

type ChatMessage 
  @model
  @auth(rules: [{ allow: owner, ownerField: "authorId" }]) {
  id: ID!
  author: User @connection(name: "UserMessages", keyField: "authorId")
  authorId: String
  content: String!
  conversation: Conversation! @connection(name: "ConvoMsgs")
  messageConversationId: ID!
  createdAt: String
  updatedAt: String
}

type ConvoLink 
  @model(
    mutations: { create: "createConvoLink", update: "updateConvoLink" }
    queries: null
    subscriptions: null
  ) {
  id: ID!
  user: User! @connection(name: "UserLinks")
  convoLinkUserId: ID
  conversation: Conversation! @connection(name: "AssociatedLinks")
  convoLinkConversationId: ID!
  createdAt: String
  updatedAt: String
}

Swift code

func createConvo(){
      let conversation = Conversation( messages: List<ChatMessage>.init(), associated: List<ConvoLink>.init(),name: "convo", members: [currentUserSub, recieverUserSub])
        _ = Amplify.API.mutate(request: .create(conversation)) { event in
            switch event {
            case .success(let result):
                switch result {
                case .success(let convo):
                  //  DispatchQueue.main.async {
                        
                        print("Successfully created the convo: \(convo)")
                       // self.messageButton.isHidden = true
                   // }
                case .failure(let graphQLError):
                    print("Failed to create graphql \(graphQLError)")
                    //  self.checkIfOffline()
                }
            case .failure(let apiError):
                print("Failed to create a todo", apiError)
                // self.checkIfOffline()
            }
        }
}
1 Answers

When you use the auth directive on your model types, ie. @auth(rules: [{allow: owner, operations: [create, delete, update]}) requires an authenticated user to call the API.

Have the user signed in using Amplify.Auth.signIn before Amplify.API.mutate/query/subscribe?

Debugging

Since you are using the auth directive, provisioning the API would have also provisioned auth category as well. You can open the provisioned auth resource via amplify console auth and select Cognito User Pool. You can create a user via the console and it will be created in a state that requires a new password.

Then, you can run amplify console api, select GraphQL, to open the AppSync console, then navigate to the Queries tab to test out your API. When testing out your API, the Queries console should indicate which is your primary authorization mode for the API, and will require you to login. Get the web app client Id from the Cognito User Pool console, with the username of the previous user you created and the password. Once you try to login, it will prompt you to enter a new password. Once you have authenticated the user via the Queries console, you can test out your API calls

In app

If you are able to get pass the NotAuthorized error by incorporating Amplify.API.signUp/confirmSignUp/signIn flow into your app, but still seeing other issues with the API call, feel free to provide more details in an Issue over in the Github repo here: https://github.com/aws-amplify/amplify-ios/issues as the repo is actively monitored

Related