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

Amplify v6中如何通过Cognito身份池实现未认证用户API Gateway访问

问题

将Amplify从v5迁移到v6后,无法实现未认证用户调用SAM后端。

在Amplify v5中,通过以下配置可让未认证用户借助Cognito临时凭证访问后端:

import { Amplify, API } from 'aws-amplify';
Amplify.configure({
  Auth: {
    mandatorySignIn: false,
    identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab', 
    region: 'XX-XXXX-X',
  },
  API: {
    endpoints: [
      {
        name: 'MyAPIGatewayAPI',
        endpoint: 'https://1234567890-abcdefgh.amazonaws.com/XXX'
      },
    ]
  }
});

但迁移到v6后,官方迁移指南仅覆盖认证用户相关配置,未提及mandatorySignIn或未认证用户的等效配置方式。

尝试以下v6配置时,API Gateway拒绝请求,提示请求未使用Cognito身份池的临时凭证签名:

Amplify.configure({
  Auth: {
    Cognito: {
      identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab',
    }
  },
  API: {
    REST: {
      MyAPIGatewayAPI: {
        endpoint: 'https://1234567890-abcdefgh.amazonaws.com/XXX',
        region: 'XX-XXXX-X'
      }
    }
  }
});

降级回v5使用原配置一切正常,说明Cognito身份池角色和权限配置无问题,仅v6配置存在问题。

请问Amplify v6中是否有类似mandatorySignIn的方式处理未认证用户访问?

解决方案

Amplify v6中移除了mandatorySignIn配置项,要实现未认证用户访问,需调整两处核心配置:

  1. 启用未认证访客访问
    在Auth的Cognito配置中添加allowGuestAccess: true,同时指定身份池ID和区域,这是让未认证用户获取临时凭证的关键:
Auth: {
  Cognito: {
    identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab',
    region: 'XX-XXXX-X',
    allowGuestAccess: true
  }
}
  1. 指定API的认证类型为IAM
    在REST API配置中明确设置authenticationType: 'AWS_IAM',确保请求使用Cognito身份池的临时凭证签名:
API: {
  REST: {
    MyAPIGatewayAPI: {
      endpoint: 'https://1234567890-abcdefgh.amazonaws.com/XXX',
      region: 'XX-XXXX-X',
      authenticationType: 'AWS_IAM'
    }
  }
}

完整的v6配置示例:

import { Amplify } from 'aws-amplify';

Amplify.configure({
  Auth: {
    Cognito: {
      identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab',
      region: 'XX-XXXX-X',
      allowGuestAccess: true
    }
  },
  API: {
    REST: {
      MyAPIGatewayAPI: {
        endpoint: 'https://1234567890-abcdefgh.amazonaws.com/XXX',
        region: 'XX-XXXX-X',
        authenticationType: 'AWS_IAM'
      }
    }
  }
});

额外确认点:

  • Cognito身份池的未认证角色已配置允许访问目标API Gateway资源的权限(因v5正常,此步骤大概率无问题)
  • 调用API时无需执行登录操作,Amplify会自动为未认证用户获取临时IAM凭证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:22:36