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

如何为Amplify静态站点配置AWS Cognito访客认证以调用API

实现AWS Cognito访客认证(无需收集用户信息)用于Amplify API调用

1. 配置Cognito用户池的匿名访问

  • 登录AWS控制台,进入目标Cognito用户池
  • 切换到身份验证标签页,找到访客身份认证选项并启用
  • 无需配置任何用户属性要求,保持默认设置即可(不收集用户名、邮箱等信息)

2. 更新Amplify项目的认证配置

方式一:通过Amplify CLI

执行以下命令更新认证模块:

amplify update auth

在交互流程中选择启用访客访问,完成后推送变更:

amplify push

方式二:手动修改配置文件

打开项目根目录的amplifyconfiguration.json,在auth节点下添加allowGuestAccess: true:

{
  "auth": {
    "plugins": {
      "awsCognitoAuthPlugin": {
        "UserAgent": "aws-amplify-cli/2.0",
        "Version": "1.0",
        "allowGuestAccess": true,
        // 其他原有配置...
      }
    }
  }
}

3. 在React应用中实现自动匿名登录

在应用初始化时(比如根组件的useEffect钩子),调用Amplify的匿名登录方法,自动获取认证身份:

import { Auth } from 'aws-amplify';
import { useEffect } from 'react';

function App() {
  useEffect(() => {
    const initGuestAuth = async () => {
      try {
        await Auth.signInAnonymously();
        // 匿名登录成功,后续API调用会自动携带认证凭证
      } catch (err) {
        console.error('匿名身份初始化失败:', err);
      }
    };
    initGuestAuth();
  }, []);

  // 组件其他逻辑...
}

export default App;

4. 配置API的未认证访问权限

REST API

通过Amplify CLI更新REST API配置,为目标资源路径设置unauthenticated用户的访问权限:

amplify update api

选择REST API后,在权限配置环节允许未认证用户访问所需的端点(如GET /company-info)。

GraphQL API

在GraphQL schema文件中,为需要访问的模型添加未认证访问规则:

type CompanyInfo @model @auth(rules: [{ allow: unauthenticated }]) {
  id: ID!
  companyName: String!
  description: String
  contactInfo: String
}

修改后推送变更:

amplify push

5. 验证API调用

完成以上配置后,React应用调用Amplify的REST或GraphQL API时,会自动使用匿名用户的身份凭证,无需访客提供任何个人信息即可完成认证请求。

内容的提问来源于stack exchange,提问作者Arjun-Phalguna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:05:23