Last active
August 23, 2022 07:41
-
-
Save pveller/fc7660bdfaf19eed4b29b2e9415c3917 to your computer and use it in GitHub Desktop.
AWS Amplify PubSub with IoT and Cognito
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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() |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I've just come across this problem, did you find a solution? thanks.