我正在尝试将 AWS IoT 配置为与 AWS Amplify 一起使用。我总是看到错误为“ AMQJS0008I Socket closed. ”,而 CloudWatch 显示“ AUTHORIZATION_FAILURE ”。这是我配置的
- 经过身份验证的 Cognito 身份池的 I AM 策略
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"cognito-identity:*",
"mobileanalytics:PutEvents",
"cognito-sync:*",
"iot:Connect",
"iot:Publish",
"iot:Subscribe",
"iot:Receive",
"iot:GetThingShadow",
"iot:UpdateThingShadow",
"iot:DeleteThingShadow",
"iot:AttachPolicy",
"iot:AttachPrincipalPolicy"
],
"Resource": "*"
}
]
}
- Cognito Identity 的 IoT 策略
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:Connect",
"Resource": "arn:aws:iot:ap-south-1:XXXXXXX:client/${iot:ClientId}"
},
{
"Effect": "Allow",
"Action": [
"iot:Publish",
"iot:Subscribe",
"iot:Receive"
],
"Resource": "arn:aws:iot:ap-south-1:XXXXXXX:topic/*"
},
{
"Effect": "Allow",
"Action": [
"iot:UpdateThingShadow",
"iot:GetThingShadow",
"iot:DeleteThingShadow"
],
"Resource": "arn:aws:iot:ap-south-1:XXXXXXX:thing/*"
},
{
"Effect": "Allow",
"Action": [
"iot:AttachPrincipalPolicy”,
"iot:AttachPolicy"
],
"Resource": [
"*"
]
}
]
}
- 使用 AWS CLI 附加个人认知身份
aws iot attach-policy --policy-name "hub-iot-policy" --target "ap-south-1:XXXX-USER_COGNITO_IDENTITY
- 使用包使用 AWS Amplify 连接和订阅
“@aws-amplify/api": "^3.1.7",
"@aws-amplify/auth": "^3.2.4",
"@aws-amplify/core": "^3.2.4",
"@aws-amplify/pubsub": "^3.0.8”,
代码是
PubSub.addPluggable(new AWSIoTProvider({
aws_pubsub_region: config.pubsub.REGION,
aws_pubsub_endpoint: `wss://${config.pubsub.MQTT_ID}.iot.${config.pubsub.REGION}.amazonaws.com/mqtt`,
}));
PubSub.subscribe('hub31-iot-thing').subscribe({
next: data => console.log('Message received', data),
error: error => console.error(error),
close: () => console.log('Done'),
});
}
- JS 控制台抛出错误为
{provider: AWSIoTProvider, error: {…}}error: {invocationContext: undefined, errorCode: 8, errorMessage: " AMQJS0008I Socket closed. "}provider: AWSIoTProvider {_config: {…}, _clientsQueue: ClientsQueue, _topicObservers: Map(1 ), _clientIdObservers: Map(1)}
- Cloudwatch 给出错误为AUTHORIZATION_FAILURE
{
"timestamp": "2020-04-21 00:13:24.953",
"logLevel": "ERROR",
"traceId": “308de5a7-XXXX-d2d5-XXXX-7e24b6d6e0e6",
"accountId": “XXXXXXXX",
"status": "Failure",
"eventType": "Connect",
"protocol": "MQTT",
"clientId": “f5e1abef-XXXX-44af-XXXX-4a327b45481c",
"principalId": “XXXXX:CognitoIdentityCredentials",
"sourceIp": “XXXX",
"sourcePort": 59101,
"reason": "AUTHORIZATION_FAILURE",
"details": "Authorization Failure"
}