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

2023-12-29

所以我认为这个问题来自于我不太理解 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("[email protected] /cdn-cgi/l/email-protection", "notarealpassword123") // runs successfully
  await createUser("[email protected] /cdn-cgi/l/email-protection") // 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')
);

以及 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
}

最终,我正在尝试制作类似的东西example https://github.com/amazon-archives/aws-appsync-chat。我尝试阅读 aws amplify 文档,但无法正确理解身份验证如何影响 graphql 操作。


我刚刚花了几个小时来解决同样的问题。对我来说,我必须在 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 文档并没有很好地记录该过程。我希望这可以帮助其他人节省一些时间。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 AWS amplify 和 graphql 创建新用户时出现“未经授权”错误 的相关文章

随机推荐

  • C# 智能感知对于采用动态参数的方法不正确

    考虑遵循简单的类 public class SomeType public static int Fn dynamic arg return 1 和以下声明 dynamic value 10 var a SomeType Fn null v
  • 不同的类实例使用相同的内存位置

    我正在玩pickle库 当我注意到有时不同的类实例位于同一内存位置时 以下两个示例都展示了上述行为 class DemoClass def init self self name demoName example 1 for i in ra
  • 在警报对话框中显示文本视图

    在我的代码中 我有一个AlertDialog and a TextView 我想显示这个TextViewin my AlertDialog但我不知道该怎么做 我不知道如何添加View in a AlertDialog 我可以展示我的代码 但
  • 为什么我无法在 Windows 10 上安装适用于 Python 的 rpy2?

    我正在尝试安装该软件包rpy2将 R 与 Python 结合使用 但是使用 pip install 安装失败 我在 Windows 10 上将 R 和 Python 与 Microsoft Visual Studio 2017 结合使用 安
  • 如何在 Azure 中设置 smtp 服务器

    是否可以在 Azure 中设置 Windows VM 来充当 smtp 服务器 我在某处读到它违反了 Azure 政策 是否有官方文档说明了这一点 This doc https learn microsoft com en us azure
  • 当 php 返回值更改时,使用 javascript 更新 html 代码

    我想使用 php 文件的返回来不断更新 html 文档 因此我需要使用 jQuery 函数 get returnfunction php function data test data document getElementById t1
  • python 3.4 多重处理不适用于unittest

    我有一个使用多处理的单元测试 从 Python 3 2 升级到 Python 3 4 后 出现以下错误 我找不到任何提示 Python 内部发生了什么变化以及我必须改变什么才能使我的代码运行 提前致谢 Traceback most rece
  • 如何使用 GDB 在 Emacs 中调试 R 包(带有 C 代码)?

    我目前正在编写一个 R 包并通过以下方式使用编译的 C 代码RcppR 中的包 对于像我这样的非程序员来说 Rcpp 使 R 和 C 代码的交互更容易 恕我直言 我想使用 gdb 调试 C 程序中的一些错误 我用 google 搜索了一下
  • 如何使用 VERTX 处理程序获取 POST 表单数据?

    我可以使用缓冲区处理程序获取表单数据 但它是一个 void 函数 我无法返回表单数据值 总共有大约 4 7 个表单 我不想最终一遍又一遍地编写相同的处理程序 因为默认函数是 void html a href activateUserPage
  • ASP.NET MVC 5 Identity 2.0、Windows Auth、具有角色属性的用户模型

    我正在尝试创建一个使用 Windows 身份验证但使用从用户模型中提取的角色的 MVC5 应用程序 我到处搜索示例 但我能找到的唯一示例是基于旧的 ASP NET 身份框架的 有人愿意指出我正确的方向吗 Thanks 所以我想出了一种方法来
  • 用户使用 Firebase Auth 和 Swift 验证其电子邮件后,如何重定向回我的应用?

    当用户在我的应用程序中注册时 他们会收到一个弹出窗口 显示 请验证您的电子邮件 然后登录 当用户单击 确定 时 他们将进入登录页面 此时 用户应转到邮件应用 iPhone 并单击从 Firebase 发送给他们的链接 单击此链接当前会打开
  • 从 NUnit 测试代码创建 iOS UI 组件

    我正在尝试为一些以编程方式创建 UIButtons 的代码编写单元测试 但是当我从测试中调用此代码时 我得到了NullReferenceException 在调试器中单步执行 看起来像UIButton FromType 返回空值 这是我正在
  • Corrgram 包装水平和垂直标签

    我正在尝试使用 Corrgram 包中的 labels 参数来绘制垂直轴和水平轴 但遇到了严重的困难 我尝试通过 labels 参数传递我的变量名称 但我的标签仍然在对角线上 我的代码如下 correlations lt c var1 va
  • 在没有模型的数据存储中查询

    我正在尝试在 appengine 中创建一个应用程序来搜索键列表 然后使用此列表从数据存储中删除这些记录 此服务必须是通用服务 因此我无法使用仅按名称搜索的模型当然 可以通过应用程序引擎功能来做到这一点吗 下面是我的代码 但它要求我有一个模
  • Add() 方法为 Code-First 实体框架中的链接模型添加重复行

    以下是将贷款请求添加到数据库的操作 HttpPost public ActionResult Add Models ViewModels Loans LoanEditorViewModel loanEditorViewModel if Mo
  • 如何在 PDO 准备语句中使用 LIKE 子句? [复制]

    这个问题在这里已经有答案了 我有一个这样的sql查询 SELECT FROM tbl name WHERE title Like needle 当我使用此语句手动查询 MySQL 数据库时 它起作用了 但是当我将它与 PDO 一起使用并使用
  • 在 Windows 上安装 git:Git Bash Here 或 git-cheetah shell 扩展?

    我正在 Windows XP 上安装 Git 在安装过程中 安装程序会询问我是否想要 1 上下文菜单条目 Git Bash Here 以及 Git GUI Here 选项 or 2 git cheetah shell 扩展 仅限 32 位
  • Pyspark:自定义窗口函数

    我目前正在尝试提取 PySpark 数据框中连续出现的一系列事件 并对它们进行排序 排名 如下所示 为了方便起见 我已通过以下方式对初始数据框进行了排序 user id and timestamp df ini user id timest
  • 移位是 O(1) 还是 O(n)?

    是否轮班操作O 1 or O n 计算机通常需要更多的操作来移动 31 位而不是移动 1 位 这是否有意义 或者说这是否有意义操作次数换档所需的是constant不管我们需要转移多少地方 PS 想知道是否hardware是一个合适的标签 某
  • 使用 AWS amplify 和 graphql 创建新用户时出现“未经授权”错误

    所以我认为这个问题来自于我不太理解 AWS cognito 用户池和 graphql 模式中的身份验证规则之间的关系 当我运行下面的代码时 我收到消息 未授权访问 User 类型上的 createUser import React from