Skip to content

Instantly share code, notes, and snippets.

@pveller pveller/pubsub.js
Last active Aug 21, 2019

Embed
What would you like to do?
AWS Amplify PubSub with IoT and Cognito
/*
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()
@beninst

This comment has been minimized.

Copy link

commented Dec 29, 2018

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.

@Vingtoft

This comment has been minimized.

Copy link

commented Jan 3, 2019

Nice!

@JL00001

This comment has been minimized.

Copy link

commented Jan 4, 2019

Thanks for this. Been searching for this for a week. Works like a charm.

@leogonzalez

This comment has been minimized.

Copy link

commented Feb 11, 2019

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

@evgineyworker

This comment has been minimized.

Copy link

commented Apr 17, 2019

Same CORS issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.