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

如何通过React UI直接触发AWS Step Functions(非API Gateway方式)

无需API Gateway直接从React触发AWS Step Functions的方案

当然可以直接实现——你可以用AWS JavaScript SDK v3结合Amazon Cognito身份池来完成,不需要经过API Gateway。核心思路是通过Cognito为前端应用提供合法的AWS身份凭证,让前端直接调用Step Functions的StartExecution API。

前置准备

  1. 配置Cognito身份池

    • 创建一个Cognito身份池(生产环境建议仅允许认证用户访问,避免未认证用户滥用权限)
    • 给身份池关联的IAM角色添加权限,允许调用Step Functions的启动执行动作。示例IAM策略如下:
      {
        "Version": "2012-10-17",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": "states:StartExecution",
            "Resource": "arn:aws:states:你的AWS区域:你的AWS账号ID:stateMachine:你的状态机名称"
          }
        ]
      }
      
  2. 安装依赖
    在React项目中安装所需的AWS SDK包:

    npm install @aws-sdk/client-sfn @aws-sdk/credential-provider-cognito-identity @aws-sdk/util-credentials
    

React组件代码示例

import { useState } from 'react';
import { SFNClient, StartExecutionCommand } from '@aws-sdk/client-sfn';
import { fromCognitoIdentityPool } from '@aws-sdk/credential-provider-cognito-identity';

// 替换为你的AWS配置信息
const AWS_CONFIG = {
  region: 'us-east-1', // 你的AWS区域
  identityPoolId: 'us-east-1:xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', // Cognito身份池ID
  stateMachineArn: 'arn:aws:states:us-east-1:123456789012:stateMachine:MyStateMachine' // Step Function ARN
};

// 初始化Step Functions客户端
const sfnClient = new SFNClient({
  region: AWS_CONFIG.region,
  credentials: fromCognitoIdentityPool({
    clientConfig: { region: AWS_CONFIG.region },
    identityPoolId: AWS_CONFIG.identityPoolId
  })
});

export default function StepFunctionTriggerButton() {
  const [isLoading, setIsLoading] = useState(false);
  const [executionResult, setExecutionResult] = useState(null);
  const [error, setError] = useState(null);

  const triggerStepFunction = async () => {
    setIsLoading(true);
    setError(null);
    setExecutionResult(null);

    try {
      // 构造启动执行的命令,输入参数根据你的状态机需求调整
      const command = new StartExecutionCommand({
        stateMachineArn: AWS_CONFIG.stateMachineArn,
        input: JSON.stringify({
          exampleParam: '来自React前端的触发请求',
          timestamp: new Date().toISOString()
        })
      });

      const response = await sfnClient.send(command);
      setExecutionResult(`执行已启动,执行ARN:${response.executionArn}`);
    } catch (err) {
      setError(`触发失败:${err.message}`);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      <button onClick={triggerStepFunction} disabled={isLoading} style={{ padding: '8px 16px', cursor: 'pointer' }}>
        {isLoading ? '触发中...' : '启动Step Function'}
      </button>
      {executionResult && <p style={{ color: '#2ecc71', marginTop: '10px' }}>{executionResult}</p>}
      {error && <p style={{ color: '#e74c3c', marginTop: '10px' }}>{error}</p>}
    </div>
  );
}

关键注意事项

  • 权限最小化:生产环境中严格控制IAM角色的权限范围,仅允许访问指定的Step Function资源,避免过度授权
  • 环境变量管理:不要硬编码AWS配置信息,建议通过.env文件注入环境变量(如REACT_APP_AWS_REGION)
  • 用户认证:如果是面向公开的应用,必须使用Cognito用户池管理认证用户,禁止开放未认证用户的权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:35:13