使用 AWS amplify 和 grahql 创建新用户时出现“未经授权”错误

pat*_*rds 6 amazon-web-services reactjs graphql aws-amplify

所以我认为这个问题来自于我不太理解 AWS cognito 用户池和 graphql 模式中的身份验证规则之间的关系。

当我运行下面的代码时,我收到消息“未授权访问 User 类型的 createUser”。

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 (
    <div className="App">
      Hello
    </div>
  );
}

export default withAuthenticator(App);
Run Code Online (Sandbox Code Playgroud)

其他相关代码是我的index.js:

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 = () => (
  <ApolloProvider client={client}>
      <App/>
  </ApolloProvider>
)

ReactDOM.render(
  <WithProvider/>,
  document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)

以及 User 对象的架构定义:

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
}
Run Code Online (Sandbox Code Playgroud)

最终,我正在尝试制作与此示例类似的东西。我尝试阅读 aws amplify 文档,但无法正确理解身份验证如何影响 graphql 操作。

小智 9

我刚刚花了几个小时来解决同样的问题。对我来说,我必须在 graphql 请求上指定 authMode。

而不是做这样的事情:

await API.graphql(graphqlOperation(createFamily, {input: family}))
Run Code Online (Sandbox Code Playgroud)

我不得不使用这个:

await API.graphql({
        query: createFamily,
        variables: {input: family},
        authMode: 'AMAZON_COGNITO_USER_POOLS'
      })
Run Code Online (Sandbox Code Playgroud)

我确实尝试了用户模式的解决方案。但是,我对架构所做的任何操作都无效(包括按指示添加@aws_cognito_user_pools)。

不幸的是,Amplify 文档并没有很好地记录该过程。我希望这可以帮助其他人节省一些时间。


pat*_*rds 1

非常确定解决方案是将 @aws_cognito_user_pools 添加到用户的架构定义中。我还对其进行了更改,以允许所有者做任何他们想做的事情,但在他们无法查询之前。

type User 
  @model 
  @auth(rules: [{ allow: owner}])
  @aws_cognito_user_pools {
  id: ID!
  username: String!
  conversations: [ConvoLink] @connection(name: "UserLinks")
  messages: [Message] @connection(name: "UserMessages")
    createdAt: String
    updatedAt: String
}
Run Code Online (Sandbox Code Playgroud)