AWS Amplify中Lambda调用GraphQL API遇权限错误求助
调用GraphQL API的Lambda函数出现未授权错误排查
我按照AWS Amplify相关文档创建调用GraphQL API的Lambda函数,但收到Not Authorized to access updateCustomUser on type Mutation错误。文档说明CLI会自动配置Lambda执行IAM角色以调用GraphQL API,但异常仍存在,求排查思路。
CustomUser模型定义
type CustomUser @model @auth(rules: [{allow: private, provider: iam}]) { id: ID! userId: String enrolledFor: CourseType }
Lambda函数代码
import crypto from '@aws-crypto/sha256-js'; import { defaultProvider } from '@aws-sdk/credential-provider-node'; import { SignatureV4 } from '@aws-sdk/signature-v4'; import { HttpRequest } from '@aws-sdk/protocol-http'; import { default as fetch, Request } from 'node-fetch'; const { Sha256 } = crypto; const GRAPHQL_ENDPOINT = process.env.API_<YOUR_API_NAME>_GRAPHQLAPIENDPOINTOUTPUT; const AWS_REGION = process.env.AWS_REGION || 'us-east-1'; const mutation = /* GraphQL */ ` mutation UpdateCustomUser($input: UpdateCustomUserInput!) { updateCustomUser(input: $input) { id enrolledFor } } `; /** * @type {import('@types/aws-lambda').APIGatewayProxyHandler} */ export const handler = async (event) => { console.log(`EVENT: ${JSON.stringify(event)}`); const endpoint = new URL(GRAPHQL_ENDPOINT); const signer = new SignatureV4({ credentials: defaultProvider(), region: AWS_REGION, service: 'appsync', sha256: Sha256 }); const variables = { input: { id: event.userId, isEnrolledFor: "CS" }, }; const requestToBeSigned = new HttpRequest({ method: "POST", headers: { "Content-Type": "application/json", host: endpoint.host, }, hostname: endpoint.host, body: JSON.stringify({ query: mutation, variables }), path: endpoint.pathname, }); const signed = await signer.sign(requestToBeSigned); const request = new Request(endpoint, signed); let statusCode = 200; let body; let response; try { response = await fetch(request); body = await response.json(); if (body.errors) statusCode = 400; } catch (error) { statusCode = 500; body = { errors: [ { message: error.message } ] }; } return { statusCode, body: JSON.stringify(body) }; };
排查思路建议
- 检查Lambda执行角色权限:确认角色是否包含
appsync:GraphQL权限,且资源范围覆盖你的GraphQL API ARN。可在IAM控制台查看角色权限策略,确保存在类似语句:{ "Effect": "Allow", "Action": "appsync:GraphQL", "Resource": "arn:aws:appsync:<REGION>:<ACCOUNT_ID>:apis/<API_ID>/*" } - 修正字段名不一致问题:代码中变量使用
isEnrolledFor,但模型定义字段为enrolledFor,字段名不匹配可能间接触发授权异常,需改为enrolledFor。 - 验证签名逻辑:确认
SignatureV4配置的service为appsync,区域与API所在区域一致,可在Lambda日志打印签名后的请求头,检查Authorization等字段是否正确生成。 - 确认@auth规则生效:重新部署API,确保
@auth(rules: [{allow: private, provider: iam}])规则已正确应用到updateCustomUsermutation,可在AppSync控制台Schema页面查看生成的授权规则。 - 检查API端点环境变量:确认
GRAPHQL_ENDPOINT已替换为实际API名称,环境变量值正确指向AppSync API端点。 - 查看AppSync日志:启用AppSync的CloudWatch日志,获取授权拒绝的详细原因,排查具体权限缺失或规则不匹配问题。
内容的提问来源于stack exchange,提问作者Sulove Dahal
相关产品推荐
相关产品推荐

