Question:
So I think this issue comes from me not quite understanding the relationship between AWS cognito user pools and the auth rules in a graphql schema.
When I run the code below, I get the message “Not Authorized to access createUser on type User”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
import React from 'react'; import { Auth, API, graphqlOperation } from 'aws-amplify'; import { withAuthenticator } from "@aws-amplify/ui-react"; // This was created automatically from the schema by aws amplify const CreateUser = /* GraphQL */ ` mutation CreateUser( $input: CreateUserInput! $condition: ModelUserConditionInput ) { createUser(input: $input, condition: $condition) { id username conversations { items { id convoLinkUserId convoLinkConversationId createdAt updatedAt } nextToken } messages { items { id authorId content messageConversationId createdAt updatedAt } nextToken } createdAt updatedAt } } `; async function signIn(username, password) { try { const user = await Auth.signIn(username, password); const { attributes } = user; console.log("User", attributes) return user } catch (error) { console.log('error signing in', error); } } async function createUser(id) { // creating a new user in the dynamodb table try { const newUser = {input: {username: id, id}} console.log("Creating new user", newUser) await API.graphql(graphqlOperation(CreateUser, newUser)) } catch (err) { console.log('Error creating user! :', err) } } async function testApiCalls() { await signIn("test@test.com", "notarealpassword123") // runs successfully await createUser("test@test.com") // where the error happens } function App() { testApiCalls() return ( Hello ); } export default withAuthenticator(App); |
Other relevant code would be my index.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import Amplify, { Auth } from 'aws-amplify'; import AWSAppSyncClient from 'aws-appsync' import aws_config from './aws-exports'; import { ApolloProvider } from '@apollo/client'; Amplify.configure(aws_config); aws_config.graphql_headers = async () => { const currentSession = await Auth.currentSession(); return { Authorization: currentSession.getIdToken().getJwtToken() }; }; const client = new AWSAppSyncClient({ url: aws_config.aws_appsync_graphqlEndpoint, region: aws_config.aws_appsync_region, auth: { type: aws_config.aws_appsync_authenticationType, // AMAZON_COGNITO_USER_POOLS jwtToken: async () => (await Auth.currentSession()).idToken.jwtToken } }); const WithProvider = () => ( ) ReactDOM.render( document.getElementById('root') ); |
And the schema definition for the User object:
1 2 3 4 5 6 7 8 9 10 11 |
type User @model @auth(rules: [{ allow: owner, ownerField: "id", queries: null }]) { id: ID! username: String! conversations: [ConvoLink] @connection(name: "UserLinks") messages: [Message] @connection(name: "UserMessages") createdAt: String updatedAt: String } |
Ultimately, I’m trying to make something similar to this example. I’ve tried reading the aws amplify docs but haven’t been able to properly understand how the graphql operations are effected by the authentication.
Answer:
I just spent several hours battling this same issue. For me, I had to specify the authMode on the graphql request.
Rather than doing something like this:
1 2 |
await API.graphql(graphqlOperation(createFamily, {input: family})) |
I had to use this:
1 2 3 4 5 6 |
await API.graphql({ query: createFamily, variables: {input: family}, authMode: 'AMAZON_COGNITO_USER_POOLS' }) |
I did try the solution from user patwords. However, nothing I did on the schema was effective (including adding @aws_cognito_user_pools as indicated).
Unfortunately, the Amplify documentation does not do a good job documenting the process. I hope this helps someone else save a bit of time.