升级AWS SDK v3后,Lambda调用IoT Data Plane获取Thing Shadow遇403错误
AWS SDK v3 Lambda调用GetThingShadowCommand返回403 ForbiddenException排查与解决
问题场景
Lambda服务中升级AWS SDK到v3版本后,使用IoTDataPlaneClient调用GetThingShadowCommand获取Thing Shadow时,返回403 ForbiddenException错误。已在Serverless配置中添加了IoT相关权限,但问题依旧。
排查与解决步骤
1. 修正IAM权限动作前缀
AWS IoT控制平面与数据平面的IAM动作前缀不同:
- 控制平面动作前缀为
iot:(比如iot:CreateThing) - 数据平面动作前缀为
iot-data:(比如iot-data:GetThingShadow)
之前配置的iot:GetThingShadow属于控制平面权限,无法授权数据平面的GetThingShadow API调用。
解决方法:修改Serverless配置中的权限动作列表,替换为iot-data:前缀的动作:
{ "Effect": "Allow", "Action": [ "iot-data:Publish", "iot-data:GetThingShadow", "iot-data:ListNamedShadowsForThing", "iot-data:UpdateThingShadow", "iot-data:DeleteThingShadow" ], "Resource": ["*"] }
2. 验证Thing名称与Shadow名称正确性
- 确认
dispenser.serial对应的Thing已在当前AWS区域的IoT Core中创建 - 检查
shadowName: "Device_Shadow"是否为该Thing已存在的命名Shadow(若使用默认Shadow,可省略该参数)
解决方法:在IoT Core控制台中核对Thing和Shadow的名称,同时在代码中添加日志输出dispenser.serial的值,确认参数无误。
3. 检查Lambda执行角色的权限边界
如果Lambda执行角色配置了权限边界,即使已添加IoT权限,权限边界可能会限制该角色的实际权限范围。
解决方法:进入Lambda控制台,查看执行角色的权限边界策略,确保其包含iot-data:GetThingShadow等必要的动作权限。
4. 确认SDK客户端区域配置
确保IoTDataPlaneClient配置的区域与Thing所在的AWS区域完全一致,环境变量process.env.DEPLOYMENT_REGION可能存在加载错误。
解决方法:验证环境变量值,必要时临时硬编码区域进行测试,比如:
const iotDataPlaneClient = new IoTDataPlaneClient({ region: 'us-east-1' // 替换为Thing所在区域 });
修正后的代码示例
import { GetThingShadowCommand, GetThingShadowCommandInput, IoTDataPlaneClient } from "@aws-sdk/client-iot-data-plane"; public async getData(dispenserId: string): Promise<object> { try { const dispenser = await Dispenser.findById(dispenserId); const iotDataPlaneClient = new IoTDataPlaneClient({ region: process.env.DEPLOYMENT_REGION || 'your-target-region' }); const input: GetThingShadowCommandInput = { thingName: dispenser.serial, shadowName: "Device_Shadow", }; const command = new GetThingShadowCommand(input); const response = await iotDataPlaneClient.send(command); const shadow = JSON.parse(response.payload.toString()); return shadow; } catch (err) { console.error('获取Thing Shadow失败:', JSON.stringify(err, null, 2)); throw err; } }
内容的提问来源于stack exchange,提问作者massimiliano manselli
相关产品推荐
相关产品推荐

