Amplify pubsub subscribe won't work on authenticated user

0

I have a react app with a very simple page that subscribes to a topic once the page is loaded. I followed the instructions from HERE and I've created the cognito user pool and identity pool and assign the correct policies. Also I attached an IoT policy to the Identity Pool Id. I assigned permissions to subscribe to a topic for both, Authenticated and Unauthenticated users

Now, I test the pubsub subscribe to topic on a test page when the page loads and there is no Authenticated User, there it loads and subscribes to the topic and receives messages. No problem. But when the user is authenticated and gets into the page, Amplify throws an UNDEFINED error. Any ideas what I should be doing wrong? or where can I look and how to get more information on this error?

Below are the debug messages I've got Here is what I have in index.js

import App from './App';
import { Amplify} from 'aws-amplify';
import { AWSIoTProvider } from '@aws-amplify/pubsub';

mplify.Logger.LOG_LEVEL = 'DEBUG';

Amplify.configure({
    Auth: {      
      region: config.cognito.REGION,
      userPoolId: config.cognito.USER_POOL_ID,
      identityPoolId: config.cognito.IDENTITY_POOL_ID,
      userPoolWebClientId: config.cognito.APP_CLIENT_ID,
    }
  });

  Amplify.addPluggable(
    new AWSIoTProvider({
      aws_pubsub_region: config.iot.REGION,
      aws_pubsub_endpoint: config.iot.PUBSUB_ENDPOINT,
    })
  );

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

here is what I have in the test page

import {PubSub } from 'aws-amplify';

export default function Space() { 
    let mqttSubscription;

    useEffect(() => {
       function subscribeToShadowUpdates() { 
        mqttSubscription = PubSub.subscribe('$aws/things/+/shadow/update/documents').subscribe({
            //next: (data) => console.log(JSON.stringify(data, null, 2)),
            next: (data) => console.log(data),
            error: (error) => console.log('ERROR: ', error),
            close: () => console.log('Done'),
          });
      };
        
       subscribeToShadowUpdates(); 

      }, []);

      useEffect(() => {
        return () => {
           mqttSubscription.unsubscribe();
        }
      }, []);
  
    return ( 
        <div>
         Test
        </div>
    )

}

Logs with UNAUTHENTICATED User

ConsoleLogger.ts:125 [DEBUG] 25:29.177 Amplify - amplify config {Auth: {…}, API: {…}}
ConsoleLogger.ts:115 [DEBUG] 25:29.177 AuthClass - configure Auth
ConsoleLogger.ts:125 [DEBUG] 25:29.177 Parser - parse config (3) [{…}, 'to amplifyconfig', {…}]
ConsoleLogger.ts:125 [DEBUG] 25:29.178 Hub - Dispatching to auth with  {event: 'configured', data: null, message: 'The Auth category has been configured successfully'}
ConsoleLogger.ts:125 [DEBUG] 25:29.178 RestAPI - configure Rest API {opt: {…}}
ConsoleLogger.ts:115 [DEBUG] 25:29.178 RestAPI - create Rest API instance
ConsoleLogger.ts:125 [DEBUG] 25:29.178 RestClient - API Options {endpoints: Array(1), Auth: {…}}
ConsoleLogger.ts:115 [DEBUG] 25:29.179 I18n - configure I18n
ConsoleLogger.ts:115 [DEBUG] 25:29.179 I18n - create I18n instance
ConsoleLogger.ts:125 [DEBUG] 25:29.179 PubSub - configure PubSub {opt: {…}}
ConsoleLogger.ts:125 [DEBUG] 25:29.179 GraphQLAPI - configure GraphQL API {opt: {…}}
ConsoleLogger.ts:115 [DEBUG] 25:29.179 GraphQLAPI - create Rest instance
ConsoleLogger.ts:125 [DEBUG] 25:29.179 RestClient - API Options {Auth: {…}, endpoints: Array(1)}
ConsoleLogger.ts:125 [DEBUG] 25:29.179 RestAPI - configure Rest API {opt: {…}}
ConsoleLogger.ts:115 [DEBUG] 25:29.179 RestAPI - create Rest API instance
ConsoleLogger.ts:125 [DEBUG] 25:29.179 RestClient - API Options {endpoints: Array(1), Auth: {…}}
ConsoleLogger.ts:125 [DEBUG] 25:29.180 GraphQLAPI - configure GraphQL API {opt: {…}}
ConsoleLogger.ts:115 [DEBUG] 25:29.180 GraphQLAPI - create Rest instance
ConsoleLogger.ts:125 [DEBUG] 25:29.180 RestClient - API Options {Auth: {…}, endpoints: Array(1)}
ConsoleLogger.ts:125 [DEBUG] 25:29.181 AbstractPubSubProvider - configure AWSIoTProvider {Auth: {…}, API: {…}, aws_pubsub_region: 'us-east-2', aws_pubsub_endpoint: 'wss://a3e8rmm32eyr8h-ats.iot.us-east-2.amazonaws.com/mqtt', clientId: '72df23de-feed-4a8f-aa8d-80ce14d5160b'}
ConsoleLogger.ts:125 [DEBUG] 25:30.377 PubSub - subscribe options undefined
ConsoleLogger.ts:125 [DEBUG] 25:30.377 MqttOverWSProvider - Subscribing to topic(s) $aws/things/+/shadow/update/documents
ConsoleLogger.ts:115 [DEBUG] 25:30.378 Credentials - getting credentials
ConsoleLogger.ts:115 [DEBUG] 25:30.378 Credentials - picking up credentials
ConsoleLogger.ts:115 [DEBUG] 25:30.378 Credentials - getting new cred promise
ConsoleLogger.ts:115 [DEBUG] 25:30.379 Credentials - checking if credentials exists and not expired
ConsoleLogger.ts:115 [DEBUG] 25:30.379 Credentials - need to get a new credential or refresh the existing one
ConsoleLogger.ts:115 [DEBUG] 25:30.379 Credentials - no credentials for expiration check
ConsoleLogger.ts:115 [DEBUG] 25:30.379 AuthClass - Getting current user credentials
ConsoleLogger.ts:115 [DEBUG] 25:30.384 AuthClass - Getting current session
ConsoleLogger.ts:115 [DEBUG] 25:30.384 AuthClass - Failed to get user from user pool
ConsoleLogger.ts:125 [DEBUG] 25:30.384 AuthClass - Failed to get the current user No current user
ConsoleLogger.ts:115 [DEBUG] 25:30.384 AuthClass - getting guest credentials
ConsoleLogger.ts:115 [DEBUG] 25:30.384 Credentials - setting credentials for guest
ConsoleLogger.ts:125 [DEBUG] 25:30.920 Credentials - Load credentials successfully {identityId: 'us-east-2:xxx', accessKeyId: 'xxxx', secretAccessKey: 'xxx', sessionToken: 'xxx…xxx', expiration: Wed Nov 02 2022 11:25:30 GMT+0100 (Central European Standard Time)}
ConsoleLogger.ts:118 [DEBUG] 25:30.924 Signer {region: 'xx-xxx-x', service: 'iotdevicegateway'}
ConsoleLogger.ts:125 [DEBUG] 25:30.926 MqttOverWSProvider - Creating new MQTT client 72df23de-feed-4a8f-aa8d-80ce14d5160b

Logs with AUTHENTICATED USER

[DEBUG] 27:26.427 Credentials - checking if credentials exists and not expired
ConsoleLogger.ts:125 
[DEBUG] 27:26.427 Credentials - are these credentials expired? {accessKeyId: 'xxx', secretAccessKey: 'xxx', sessionToken: 'xxxxxx', expiration: Wed Nov 02 2022 11:27:22 GMT+0100 (Central European Standard Time), identityId: 'us-east-2:xxxxx', …}
ConsoleLogger.ts:115
 [DEBUG] 27:26.427 Credentials - credentials not changed and not expired, directly return
ConsoleLogger.ts:118 
[DEBUG] 27:26.434 Signer {region: 'us-east-2', service: 'iotdevicegateway'}
ConsoleLogger.ts:125 
[DEBUG] 27:26.436 MqttOverWSProvider - Creating new MQTT client 09db81a1-f3eb-4e70-95fb-d286da21b209
ERROR:  {provider: AWSIoTProvider, error: undefined}
[DEBUG] 27:26.952 MqttOverWSProvider - Unsubscribing from topic(s) $aws/things/+/shadow/update/documents

And this is the JSON in undefined

{
    "provider": {
        "_config": {
            "Auth": {
                "region": "us-east-2",
                "userPoolId": "us-east-2_xxxx",
                "identityPoolId": "us-east-2:xxxxx",
                "userPoolWebClientId": "xxxx"
            },
            "API": {
                "endpoints": [
                    {
                        "name": "spaces",
                        "endpoint": "https://xxxxx.execute-api.us-xxx-x.amazonaws.com",
                        "region": "us-xxx-x"
                    }
                ]
            },
            "aws_pubsub_region": "us-east-2",
            "aws_pubsub_endpoint": "wss://xxxx-ats.iot.us-xxx-x.amazonaws.com/mqtt",
            "clientId": "09db81a1-f3eb-4e70-95fb-d286da21b209"
        },
        "_clientsQueue": {
            "promises": {}
        },
        "connectionStateMonitor": {
            "_linkedConnectionState": {
                "networkState": "connected",
                "connectionState": "disconnected",
                "intendedConnectionState": "disconnected",
                "keepAliveState": "healthy"
            },
            "_linkedConnectionStateObservable": {},
            "_linkedConnectionStateObserver": {
                "_subscription": {
                    "_observer": {},
                    "_state": "ready"
                }
            }
        },
        "_topicObservers": {},
        "_clientIdObservers": {}
    }
}
```
1 Answer
0
Accepted Answer

I totally missed the fact that I need to attach a policy to the cognito identity of every user that logs into the application. So I end up creating a code snippet that do that. thanks to @Greg_B for the answer on this post . I used THIS CODE as a guide

The difficult thing was to always get Undefined error in my browser. So I went to AWS CLoudwatch and checked the IoT logs only to find that there were several attempts to connect to MQTT with authorization error. That gave me the clue to fix it.

:)

mvp
answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions