- Amplify からAWS IoT CoreへMQTTのメッセージをPublishしたく、試しました。(vueを利用した場合の実装例です)
- CognitoのFederated Identity を利用して認証機能を実現します。
- https://docs.aws.amazon.com/ja_jp/cognito/latest/developerguide/identity-pools.html
基本的なやりかた
MQTT 接続
Auth.currentCredentials().then(info => {
const cognitoIdentityId = info._identityId;
console.log("cognito identity id", cognitoIdentityId); // debug
Amplify.addPluggable(new AWSIoTProvider({
aws_pubsub_region: 'ap-northeast-1',
aws_pubsub_endpoint: 'wss://xxxxx.iot.ap-northeast-1.amazonaws.com/mqtt',
clientId: 'your-client-id'
}));
});
Cognito ログイン画面
<amplify-authenticator></amplify-authenticator>
publish
import { PubSub } from 'aws-amplify';
export default {
// 中略
methods: {
publish: async function () {
await PubSub.publish('v1/topic/abc', {
"key": "value"
});
}
}
ハマったところ
errorCode: 8, errorMessage: AMQJS0008I Socket closed.
PubSub.publishのエラーで上記が出た。
こちらの記事を参考にして、Cognito のIdentity IDに対して、コマンドライン上からIoTのポリシーをアタッチすることで解決しました。
https://qiita.com/poruruba/items/34d4d7247d152b1ec933
aws iot attach-policy --policy-name "<IoT Coreで作成したポリシー>" --target <Identity ID>
Identity ID は、GUI上で、CognitoのFederated Identity のページで、Identity Browserを選択すると表示されます。上述のMQTT接続のところで、 info._identityId;
でも取得できます。