AWS IoT Android application over MQTT throws MqttException (0) - java.io.IOException: Already connected

前端 未结 3 1669
野的像风
野的像风 2020-12-19 06:54

I am trying to use \'Authenticate using Cognito-Identity with Cognito user pool\' in my Android application. My Cognito user pool authentication works well, when I run that

3条回答
  •  梦毁少年i
    2020-12-19 07:06

    I beat my head up with this almost a week.

    Full course of action -> After succesfull login you will have a jwt token

    String idToken = cognitoUserSession.getIdToken().getJWTToken();
    

    put it into a map

    Map logins = new HashMap(); 
    //fill it with Cognito User token
    logins.put("cognito-idp..amazonaws.com/", idToken);
    

    then use it to set in two places (not stated in any documentation!)

    CognitoCachingCredentialsProvider credentialsProvider = new 
    CognitoCachingCredentialsProvider(context, IDENTITY_POOL_ID, REGION);
    credentialsProvider.setLogins(logins);
    

    and

    AmazonCognitoIdentity cognitoIdentity = new AmazonCognitoIdentityClient(credentialsProvider);
    GetIdRequest getIdReq = new GetIdRequest();
    getIdReq.setLogins(logins); //or if you have already set provider logins just use credentialsProvider.getLogins()
    getIdReq.setIdentityPoolId(COGNITO_POOL_ID);
    GetIdResult getIdRes = cognitoIdentity.getId(getIdReq);
    

    after that you still nedd to make some call

    AttachPrincipalPolicyRequest attachPolicyReq = new AttachPrincipalPolicyRequest(); //in docs it called AttachPolicyRequest but it`s wrong
    attachPolicyReq.setPolicyName("allAllowed"); //name of your IOTAWS policy
    attachPolicyReq.setPrincipal(getIdRes.getIdentityId());
    new AWSIotClient(credentialsProvider).attachPrincipalPolicy(attachPolicyReq);
    

    and only after that you can enable connect button and continue like that

    mqttManager.connect(credentialsProvider, new AWSIotMqttClientStatusCallback() {
    

    Really for this small piece of code i spent a lot of time...

提交回复
热议问题