且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在AWS Amplify/AppSync React应用中正确处理未经身份验证的用户和请求?

更新时间:2022-06-25 09:43:37

  1. 请确保通过运行 amplify update auth 并手动配置设置来更新身份验证设置,以启用经过身份验证的访问和未经身份验证的访问.

  1. Make sure to update your authentication settings to enable both authenticated and unauthenticated access by running amplify update auth and configuring the settings manually.

在API请求中,您现在可以指定身份验证模式:

In an API request, you can now specify the auth mode:

const createdTodo = await API.graphql({
  query: queries.createTodo,
  variables: {input: todoDetails},
  authMode: 'AWS_IAM'
});

这里是更详细的文档

这些步骤已过时,但仍然有效:

These steps are outdated but also still work:

使用以下步骤,您可以同时允许Authenticated&未经授权的对您的AWS AppSync API的访问:

Using the following steps, you can allow both Authenticated & Unauthenticated access to your AWS AppSync API:

  1. 创建一个放大项目

amplify init

  1. 使用自定义安全配置添加身份验证:

amplify add auth

您要使用默认的身份验证和安全性配置吗?

选择要使用的身份验证/授权服务:(使用箭头键)与AWS IAM控件关联的用户注册,登录(启用图像或其他内容的每用户存储功能,Analytics(分析)等)

请为您的资源提供一个友好名称,该名称将用于在项目中标记此类别: YOURAPINAME

请输入您的身份库的名称. YOURIDPOOLNAME

允许未经身份验证的登录?(提供您可以通过AWS IAM控制的范围缩小权限)

为其余问题选择默认值

  1. 添加api

amplify add api

选择 Amazon Cognito用户池作为授权类型.

  1. 创建API

amplify push

  1. 在AppSync API仪表板设置中,将身份验证类型更改为 AWS身份和访问管理(IAM)

在客户端应用程序的 aws.exports.js 中,将 aws_appsync_authenticationType 更改为 AWS_IAM

In aws.exports.js on the client app, change aws_appsync_authenticationType to AWS_IAM

在Cognito仪表板中,单击管理身份池",然后单击确定".&点击您的身份池.

In the Cognito dashboard, click "Manage Identity Pools" & click on your identity pool.

点击编辑身份池"来查看您的未经身份验证的角色";&认证角色"

Click "Edit Identity Pool" to see your "Unauthenticated role" & "Authenticated Role"

打开IAM控制台&找到未经身份验证的角色";从第8步开始

Open the IAM console & find the "Unauthenticated role" from step 8

点击添加内联策略"

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "appsync:GraphQL"
            ],
            "Resource": [
                "arn:aws:appsync:<REGION>:<ACCOUNTID>:apis/<APIID>/types/Mutation/fields/listTodos"
            ]
        }
    ]
}

  1. 打开IAM控制台&找到已认证角色";从第8步开始

  1. Open the IAM console & find the "Authenticated role" from step 8

点击添加内联策略"

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "appsync:GraphQL"
            ],
            "Resource": [
                "arn:aws:appsync:<REGION>:<ACCOUNTID>:apis/<APIID>/types/Mutation/fields/listTodos",
                "arn:aws:appsync:<REGION>:<ACCOUNTID>:apis/<APIID>/types/Mutation/fields/createTodo"
            ]
        }
    ]
}

  1. 在index.js中,添加以下代码:

import { Auth } from 'aws-amplify'
Auth.currentCredentials()
  .then(d => console.log('data: ', d))
  .catch(e => console.log('error: ', e))

  1. 您现在应该可以在注销后进行查询,&查询和登录时会创建突变.