-
-
Save pveller/fc7660bdfaf19eed4b29b2e9415c3917 to your computer and use it in GitHub Desktop.
| /* | |
| In order to subscribe to the AWS IoT topic over WS (over MQQT), | |
| you have to make sure that your Cognito identity has a proper IoT policy attached to it. | |
| More details and the message from the official AWS support: | |
| https://github.com/aws/aws-amplify/issues/749 | |
| This code shows how you can dynamically attach a policy to the authenticated identity. | |
| Make sure that your Authenticated IAM in the Cognito User Pool has proper IoT permissions. | |
| I settled on: | |
| iot:AttachPolicy | |
| iot:AttachPrincipalPolicy | |
| iot:ListPrincipalPolicies | |
| iot:ListAttachedPolicies | |
| And the IoT policy itself has: | |
| iot:Connect | |
| iot:Subscribe | |
| iot:Receive | |
| */ | |
| import AWS from 'aws-sdk'; | |
| import { Auth, PubSub } from 'aws-amplify'; | |
| const credentials = await Auth.currentCredentials(); | |
| const iot = new AWS.Iot({ | |
| region: 'us-east-1', | |
| credentials: Auth.essentialCredentials(credentials) | |
| }); | |
| const policyName = '<Your Policy>'; | |
| const target = credentials._identityId; | |
| const { policies } = await iot.listAttachedPolicies({ target }).promise(); | |
| if (!policies.find(policy => policy.policyName === policyName)) { | |
| await iot.attachPolicy({ policyName, target }).promise(); | |
| } | |
| // safe to call PubSub.subscribe() |
Nice!
Thanks for this. Been searching for this for a week. Works like a charm.
Hi! Thanks for this, really helpful - is anyone else getting a CORS error when trying this? I am stuck a couple of days on this CORS error, and I believe calling this code from the react App.js won't work. Any ideas?
Thank you
Same CORS issue.
Thanks alot!
Hi! Thanks for this, really helpful - is anyone else getting a CORS error when trying this? I am stuck a couple of days on this CORS error, and I believe calling this code from the react App.js won't work. Any ideas?
Thank you
Hi, I've just come across this problem, did you find a solution? thanks.
Thanks Pavel!
Having same issue with CORS.
I know that some AWS service endpoints don't have CORS enabled on their (server side), and you just won't be able to call the AWS SDK commands from in a browser because of that. Maybe this is one of those cases?
Thanks a bunch! This was the only solution that worked for me after a bunch of debugging.
Hello,
thank you for providing this example. While the code in the example works for me I don't know how to subscribe/publish after attaching the policy. Do I still need to add the MqttOverWSProvider? How did you call the PubSub.subscribe() method? And Where is the Broker endpoint configured?
Thanks and best regards.