For unauthenticated cognito identities the "Identity pool anauthenticated" role is sufficient to allow connecting to the IoT MQTT broker. However for authenticated cognito identities two things are required:
The "Identity pool authenticated" role must allow access to the IoT actions you require (e.g. connect, publish etc).
You must attach an IoT policy (exactly like the ones that are attached to your devices) to the cognito identity using the AttachPrincipalPolicy API
Step 2 is where I was stuck earlier today as it was not particularly clear anywhere that this was required.
AFAIK there is no way to attach the IoT policy to a cognito user from any of the AWS web sites. However if you have the AWS command line interface setup on your machine you can do it from there. The command looks like:
aws iot attach-principal-policy --policy-name <iot-policy-name> --principal <cognito-identity-id>
The cognito identity id can be found using the Federated Identities > Your Pool > Identity browser
or you could also find it in the responses to your CognitoIdentityCredentials.get
call. It looks like this us-east-1:ba7cef62-f3eb-5be2-87e5-fffbdeed2824
For a production system you'll obviously want to automate attaching this policy, probably using a lambda function on user signup.
The section of the docs that talks about needing to attach the IoT policy can be found on this page:
For an authenticated Amazon Cognito identity to publish MQTT messages over HTTP on topic1 in your AWS account, you must specify two policies, as outlined here. The first policy must be attached to an Amazon Cognito identity pool role and allow identities from that pool to make a publish call. The second policy is attached to an Amazon Cognito user using the AWS IoT AttachPrincipalPolicy API and allows the specified Amazon Cognito user access to the topic1 topic.
Action: ["iot:*"], Resource: "*"
to each user on registration, and the same permissions (just for testing purposes) to the authenticated Cognito pool role. But now I get 403. I'm using the user identityId (us-east-1:...) as clientId in the Paho.MQTT.Client and region, AccessKeyId, and SecretKey to sign the request. – Orna