【问题标题】:'Unauthorized' error when using AWS amplify with grahql to create a new user使用 AWS amplify 和 graphql 创建新用户时出现“未经授权”错误
【发布时间】:2021-01-16 07:51:12
【问题描述】:

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

当我运行下面的代码时,我收到消息“未授权访问用户类型的 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);

其他相关代码是我的 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')
);

以及用户对象的架构定义:

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
}

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

【问题讨论】:

    标签: reactjs amazon-web-services graphql aws-amplify


    【解决方案1】:

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

    而不是做这样的事情:

    await API.graphql(graphqlOperation(createFamily, {input: family}))
    

    我不得不使用这个:

    await API.graphql({
            query: createFamily,
            variables: {input: family},
            authMode: 'AMAZON_COGNITO_USER_POOLS'
          })
    

    我确实尝试了用户密码的解决方案。但是,我在架构上所做的一切都无效(包括按指示添加 @aws_cognito_user_pools)。

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

    【讨论】:

      【解决方案2】:

      非常确定解决方案是将@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
      }
      

      【讨论】:

        猜你喜欢
        • 2022-10-24
        • 2015-03-05
        • 1970-01-01
        • 1970-01-01
        • 2020-11-15
        • 1970-01-01
        • 2020-12-17
        • 2016-06-29
        • 2021-09-23
        相关资源
        最近更新 更多