【问题标题】:How to use AMAZON_COGNITO_USER_POOLS in aws amplify API in ReactJS如何在 ReactJS 的 aws amplify API 中使用 AMAZON_COGNITO_USER_POOLS
【发布时间】:2020-04-29 16:26:45
【问题描述】:

我在 React 中有一个使用 AWS Amplify 的 API 和身份验证的应用程序。我已经配置了 API_KEY 和 AMAZON_COGNITO_USER_POOLS 以访问 API。例如,我有一个这样的 graphql 架构:

type Course @model @auth(rules: [
    # Defaults to use the "owner" field.
    {allow: owner, ownerField: "author", provider: userPools, operations: 
    [read, create, update, delete]},
    # Admin users can access any operation.
    { allow: groups, groups: ["Admin"] },
    # Next allow public access with an API Key
    {allow: public, provider: apiKey, operations: [read]}
    ]){
    id: ID!
    title: String!
    content: String!
    author: String
}

我已经推送了我的更改 (amplify push),但是当我尝试创建课程时,我收到了一个已通过 AWS Cognito 成功登录的用户的 Not Authorized to access createCourse on type Course

API.graphql({
   query: createCourse,
   variables: {input: {...course}},
   authMode: 'AMAZON_COGNITO_USER_POOLS'
})

额外信息:
我正在使用联合登录 (Google)。用户来到网站,他们通过谷歌登录。访问令牌可通过:Auth.currentSession()).getIdToken().getJwtToken() 获得,但如果我必须对此令牌执行任何操作或它会在 graphql API 调用中自动使用,我不会这样做。

【问题讨论】:

  • 请附上您的课程模型。
  • 搞错了:博客 => 课程。
  • 我试图重现您的问题,但一切似乎都很好!够了{allow: owner, ownerField: "author", provider: userPools, operations: [read, create, update, delete]},
  • 也许你的问题是在使用 API_KEY 时?
  • 我添加了额外的信息,也许您现在可以确切地看到我在做什么。联合签到有问题吗?以及如何使返回的 JWT 用于 API 访问?

标签: amazon-web-services react-native aws-amplify


【解决方案1】:

在您的类型定义中,您有 ownerField: "author",因此您应该将 Current Authenticated User 传递给输入。

course= {
        title: "titel...", 
        content: "content...", 
        author:user //Current Authenticated User
         };


获取当前认证的用户对象

Auth.currentAuthenticatedUser({
       bypassCache: false 
      }).then(user => console.log(user))
        .catch(err => console.log(err));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 2022-09-25
    • 2019-07-09
    • 1970-01-01
    • 2020-08-19
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多