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

使用Python为AWS IoT Thing附加策略时遇InvalidRequestException错误

解决AWS IoT Attach Policy到Thing时的InvalidRequestException错误

问题原因

iot_client.attach_policy()的target参数不接受IoT Thing的ARN。这个接口的作用是将策略附加到身份主体(比如IoT证书、IAM用户/角色、Cognito身份)上,而非直接绑定到Thing实体。AWS IoT的权限模型是:设备通过证书认证,策略授权证书的操作权限,再将证书与Thing关联,以此实现设备以Thing身份进行交互。

修正后的完整代码

import boto3
import os
from OpenSSL import crypto

# AWS IoT settings
iot_client = boto3.client('iot')
iot_thing_name = 'YourIoTThingName'
policy_name = 'YourPolicyName'

# 1. 创建IoT Thing
response = iot_client.create_thing(thingName=iot_thing_name)
thing_arn = response['thingArn']
print(f"Created Thing: {thing_arn}")

# 2. 创建IoT证书与密钥(会返回证书、公钥、私钥和证书ARN)
cert_response = iot_client.create_keys_and_certificate(setAsActive=True)
cert_arn = cert_response['certificateArn']
cert_pem = cert_response['certificatePem']
private_key = cert_response['keyPair']['PrivateKey']
public_key = cert_response['keyPair']['PublicKey']

print(f"Created Certificate: {cert_arn}")

# 3. 将证书附加到IoT Thing
iot_client.attach_thing_principal(thingName=iot_thing_name, principal=cert_arn)
print(f"Attached certificate to Thing: {iot_thing_name}")

# 4. 创建策略
policy_document = '''
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "iot:*",
      "Resource": "*"
    }
  ]
}
'''
policy_document = policy_document.strip()
iot_client.create_policy(policyName=policy_name, policyDocument=policy_document)
print(f"Created Policy: {policy_name}")

# 5. 将策略附加到证书(这里用证书ARN作为target)
iot_client.attach_policy(policyName=policy_name, target=cert_arn)
print(f"Attached policy to certificate: {cert_arn}")

关键步骤说明

  • 创建证书:用create_keys_and_certificate生成设备认证所需的证书和密钥,同时设置为激活状态。
  • 关联证书与Thing:通过attach_thing_principal将证书和Thing绑定,建立设备身份与Thing的关联。
  • 绑定策略到证书:最后用attach_policy把策略附加到证书ARN上,这样持有该证书的设备就能获得策略中定义的权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:49:58