首页 > 解决方案 > Lambda 函数无法访问 appsync

问题描述

我有一个由 amplify 创建的 lambda 函数,用于从 appsync 获取捐助者列表,但每次我尝试请求时它都会得到 UnauthorizedException。这是我的 lambda 函数:

const axios = require('axios');
const gql = require('graphql-tag');
const graphql = require('graphql');
const { print } = graphql;

const listDonors = gql`
    query listDonors {
        listDonors {
            items {
                id
                firstName
                lastName
            }
        }
    }
`

exports.handler = async (event) => {
    console.log("--------------------------------->");
    try {
        const graphqlData = await axios({
            url: process.env.API_DOCBACKEND_GRAPHQLAPIENDPOINTOUTPUT,
            method: 'post',
            headers: {
                'x-api-key': process.env.API_DOCBACKEND_GRAPHQLAPIIDOUTPUT
            },
            data: {
                query: print(listDonors),
            }
        });
        const body = {
            graphqlData: graphqlData.data.data.listTodos
        }
        return {
            statusCode: 200,
            body: JSON.stringify(body),
            headers: {
                "Access-Control-Allow-Origin": "*",
            }
        }
    } catch (err) {
        console.log('error posting to appsync: ', err);
    }
}

这是我的 IAM 角色:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Action": [
            "appsync:Create*",
            "appsync:StartSchemaCreation",
            "appsync:GraphQL",
            "appsync:Get*",
            "appsync:List*",
            "appsync:Update*",
            "appsync:Delete*"
        ],
        "Resource": [
            "arn:aws:appsync:us-east-1:862148551361:apis/2i62fn5z4vhtxbik3jcm33tc6e/types/Query/*",
            "arn:aws:appsync:us-east-1:862148551361:apis/2i62fn5z4vhtxbik3jcm33tc6e/types/Mutation/*",
            "arn:aws:appsync:us-east-1:862148551361:apis/2i62fn5z4vhtxbik3jcm33tc6e/types/Subscription/*"
        ],
        "Effect": "Allow"
    }
]

}

我遵循 aws amplify 文档,但它对我没有任何帮助。

标签: aws-lambdaaws-amplifyaws-appsync

解决方案


该文档似乎表明您应该将字段或 graphqlapi 传递给GraphQL权限。

  • 字段应为arn:${Partition}:appsync:${Region}:${Account}:apis/${GraphQLAPIId}/types/${TypeName}/fields/${FieldName}
  • graphqlapi 应该阅读arn:${Partition}:appsync:${Region}:${Account}:apis/${GraphQLAPIId}

在我看来,似乎arn:aws:appsync:us-east-1:xxx:apis/xxx/types/Query/*不太符合规则。

也许您应该将其替换arn:aws:appsync:us-east-1:xxx:apis/xxx"为使用graphqlapi格式

或者使用字段格式:(arn:aws:appsync:us-east-1:xxx:apis/xxx/types/Query/fields/*显然,对其他类型也这样做)?


推荐阅读