You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用API Key调用AWS Amplify GraphQL查询时遇未授权错误

解决API Key访问AppSync listTickets查询未授权问题

问题背景

我定义了如下GraphQL Schema:

type Ticket @model
  @auth(rules: [
    {allow: public, provider: apiKey},
    {allow: groups, groups: ["Admins","Moderators"], operations: [create, update, delete, read]},
    {allow: owner, ownerField: "authorizations", operations: [create, update, read]}
  ]){
  id: ID! @primaryKey
  createdBy: String!
  authorizations: [String]!
  emailCreatedBy: String!
  title: String!
  description: String!
}

通过Amplify CLI将默认授权模式设为Cognito User Pool,API Key作为次要授权模式。但使用API Key发送如下请求时:

{
    "query": "query ListTickets{listTickets{items{id}}}",
    "authMode": "API_KEY"
}

(已携带x-api-key请求头),收到未授权错误:

{
  "data": {
    "listTickets": null
  },
  "errors": [
    {
      "path": [
        "listTickets"
      ],
      "data": null,
      "errorType": "Unauthorized",
      "errorInfo": null,
      "locations": [
        {
          "line": 2,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "Not Authorized to access listTickets on type ModelTicketConnection"
    }
  ]
}

Cognito认证用户可正常访问,AppSync控制台测试也报相同错误,添加@aws_api_key指令后问题依旧。


解决方法

  1. 为public授权规则明确指定操作权限
    原Schema中{allow: public, provider: apiKey}未指定operations字段,Amplify默认不会自动为list查询授予API Key权限。修改规则,明确包含read操作:

    {allow: public, provider: apiKey, operations: [read]}
    
  2. 重新部署GraphQL资源
    修改Schema后执行:

    amplify push
    

    确保生成的Resolver更新为包含API Key的授权检查逻辑。

  3. 验证API Key及授权模式配置

    • 登录AppSync控制台,确认使用的API Key未过期且状态有效
    • 检查API的授权模式设置,确保API Key已被启用为次要授权模式
  4. 移除冲突的@aws_api_key指令
    由于已通过@auth规则配置API Key授权,无需额外添加@aws_api_key,避免授权逻辑冲突。

内容的提问来源于stack exchange,提问作者marcotw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:06:27