简体   繁体   English

无法使用 IAM 和 AppSyncClient 从 Lambda 验证到 AppSync GraphQL api

[英]Unable to auth into AppSync GraphQL api from Lambda using IAM and AppSyncClient

I'm using an amplify stack and need to perform some actions to my graphql api which has dynamodb behind it.我正在使用放大堆栈,需要对我的 graphql api 执行一些操作,它后面有 dynamodb。 The request in my lambda function returns an Unauthorized error: "Not Authorized to access getSourceSync on type SourceSync", where getSourceSync is the gql query and SourceSync is the model name.我的 lambda function 中的请求返回未经授权的错误:“未授权在 SourceSync 类型上访问 getSourceSync”,其中 getSourceSync 是 gql 查询,SourceSync 是 Z20F35E63053988DFA8C3F6 名称。

My schema.grapqhl for this particular model is set up as following.我的这个特定 model 的 schema.grapqhl 设置如下。 Note auth rule allow private provider iam:注意 auth 规则允许私有提供程序 iam:

type SourceSync @model (subscriptions: { level: off }) @auth(rules: [
    {allow: private, provider: iam}
    {allow: groups, groups: ["Admins"], provider: userPools},
    {allow: groups, groups: ["Users"], operations: [create], provider: userPools},
    {allow: groups, groupsField: "readGroups", operations: [create, read], provider: userPools},
    {allow: groups, groupsField: "editGroups", provider: userPools}]) {
    id: ID! @primaryKey
    name: String
    settings_id: ID @index(name: "bySettingsId", queryField: "sourceSyncBySettingsId")
    settings: Settings @hasOne(fields: ["settings_id"])
    childLookup: String
    createdAt: AWSDateTime!
    updatedAt: AWSDateTime!
    _createdBy: String
    _lastChangedBy: String
    _localChanges: AWSJSON
    readGroups: [String]
    editGroups: [String]
}

My lambda function's role has the following inline policy attached to it.我的 lambda 函数的角色附加了以下内联策略。 (Actual ID values have been omitted for security purposes on this post): (出于安全目的,本文省略了实际 ID 值):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "appsync:GraphQL"
            ],
            "Resource": [
                "arn:aws:appsync:us-east-1:111myaccountID:apis/11mygraphqlapiID/*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "appsync:GetType"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        }
    ]
}

And finally my lambda function is set up as follows with a simple query test:最后我的 lambda function 通过简单的查询测试设置如下:

/* stuff */

"use strict";
const axios = require("axios");
const awsAppSync = require("aws-appsync").default;
const gql = require("graphql-tag");
require("cross-fetch/polyfill");
const { PassThrough } = require("stream");
const aws = require("aws-sdk");

aws.config.update({
    region: process.env.AWS_REGION,

});

const appSync = new aws.AppSync();

const graphqlClient = new awsAppSync({
    url: process.env.API_GRAPHQLAPIENDPOINTOUTPUT,
    region: process.env.AWS_REGION,
    auth: {
        type: "AWS_IAM",
        credentials: aws.config.credentials,
    },
    disableOffline: true
});

exports.handler = async (event, context) => {
    
    console.log('context :: '+JSON.stringify(context));
    
    console.log('aws config :: '+JSON.stringify(aws.config));
    
          const sourceSyncTypes = await appSync
          .getType({
            apiId: process.env.API_GRAPHQLAPIIDOUTPUT,
            format: "JSON",
            typeName: "SourceSync",
          })
          .promise();
          console.log('ss = '+JSON.stringify(sourceSyncTypes));
    
    try {
    const qs = gql`query GetSourceSync {
  getSourceSync(id: "ov3") {
    id
    name
  }
}`;
    const res = await graphqlClient.query({query: qs, fetchPolicy: 'no-cache'});
    console.log(JSON.stringify(res));
    
    }
    catch(e) {
        console.log('ERR :: '+e);
        console.log(JSON.stringify(e));
    }
    
};

Found the solution, there seems to be an issue with triggering a rebuild of the resolvers on the api after permitting a function to access the graphql api. Found the solution, there seems to be an issue with triggering a rebuild of the resolvers on the api after permitting a function to access the graphql api. However there is a distinction to note:但是有一个区别需要注意:

  1. If the graphql api is part of an amplify app stack, then only functions created through the amplify cli for that app (ex: amplify add function ) and that are given access to the api through there will be able to access the api. If the graphql api is part of an amplify app stack, then only functions created through the amplify cli for that app (ex: amplify add function ) and that are given access to the api through there will be able to access the api.

    • additonally during the update when you either create, or update the function to give it permissions, you must ensure that during the amplify push operation, the api stack will also be updating.此外,在更新期间,当您创建或更新 function 以授予其权限时,您必须确保在放大推送操作期间,api 堆栈也将更新。 you can trigger this by simply adding or removing a space in a comment inside of your amplify/backend/api//schema.graphql file.您可以通过简单地在您的放大/后端/api//schema.graphql 文件内的注释中添加或删除空格来触发此操作。
  2. If the function was created "adhoc" directly through the aws console, but it is trying to access a graphql api that was created as part of an amplify app stack, then you will need to put that function's role in amplify/backend/api/< apiname>/custom-roles.json in the format If the function was created "adhoc" directly through the aws console, but it is trying to access a graphql api that was created as part of an amplify app stack, then you will need to put that function's role in amplify/backend/api/ <apiname>/custom-roles.json 格式

    { "adminRoleNames": ["<role name>", "<role name 2>", ...] }

Documentation references here .文档参考这里

  1. If neither your api or lambda function were created with the amplify cli as part of an app stack, then just need to give access to the graphql resources for query, mutation and subscription to the lambda's role in IAM, via inline policies or a pre-defined policy. If neither your api or lambda function were created with the amplify cli as part of an app stack, then just need to give access to the graphql resources for query, mutation and subscription to the lambda's role in IAM, via inline policies or a pre-明确的政策。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 Lambda 调用 AWS AppSync graphql API - Calling AWS AppSync graphql API from Lambda AWS Lambda function 无法访问 AppSync GraphQL API 权限被拒绝 - AWS Lambda function unable to access AppSync GraphQL API - permission denied 无法从 Lambda 调用 AppSync GraphQL api:TypeError:无法读取 Z37A6259CC0C1DAE299A78 的属性“匹配” - Unable to call AppSync GraphQL api from Lambda: TypeError: Cannot read property 'match' of null 无法使用 IAM 策略限制对 lambda 中的 API 端点的访问 - Unable to restrict access to an API endpoint in lambda using IAM policy 如何将已签名的 HTTP 请求从 AWS Lambda 发送到 AppSync GraphQL? - How to send signed HTTP request from AWS Lambda to AppSync GraphQL? AWS Appsync Graphql Java 客户端 - IAM 授权 - AWS Appsync Graphql Java Client - IAM authorisation AWS AppSync GraphQL API仅从DynamoDB返回20个项目 - AWS AppSync GraphQL API only return 20 items from DynamoDB 使用 Amazon api 网关用 REST API 包装 graphQL(appsync) - Wrapping graphQL(appsync) with REST API using Amazon api gateway 通过 Amplify 使用 AWS appsync api(GraphQL) 有什么限制? - What are the limitations of using AWS appsync api(GraphQL) through Amplify? 将 graphQL 与 API 网关(apollo-server-lambda)与 AppSync 一起使用 - Use graphQL with API Gateway (apollo-server-lambda) vs. AppSync
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM