I’m trying to connect to AWS MQTT3 via websockets with authentication from Cognito, but I’m getting Caused by: software.amazon.awssdk.crt.mqtt.MqttException: The connection was closed unexpectedly.
. What might be the problem?
This is my method for getting GetCredentialsForIdentityResponse
public GetCredentialsForIdentityResponse getCredentialsForIdentity(AuthenticationResultType accessToken, String identityId) {
try (var client = CognitoIdentityClient.builder()
.region(Region.of(region))
.build()) {
return client.getCredentialsForIdentity(
GetCredentialsForIdentityRequest.builder()
.identityId(identityId)
.logins(
Map.of(
"cognito-idp.eu-central-1.amazonaws.com/eu-central-1_XGRz3CgoY",
accessToken.idToken()))
.build());
}
}
After this I’m using GetCredentialsForIdentityResponse
to obtain MqttClientConnection
:
public MqttClientConnection buildConnection(String prefix,
String region,
String clientId,
GetCredentialsForIdentityResponse credentialsForIdentity) {
try (var builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(null, null)) {
MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {
@Override
public void onConnectionInterrupted(int errorCode) {
log.error("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
}
@Override
public void onConnectionResumed(boolean sessionPresent) {
log.error("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
}
};
return builder.withEndpoint("%s-ats.iot.%s.amazonaws.com".formatted(prefix, region))
.withWebsockets(true)
.withConnectionEventCallbacks(callbacks)
.withWebsocketSigningRegion(region)
.withClientId(clientId)
.withWebsocketCredentialsProvider(
new StaticCredentialsProvider.StaticCredentialsProviderBuilder()
.withAccessKeyId( credentialsForIdentity.credentials().accessKeyId().getBytes(UTF_8))
.withSecretAccessKey(credentialsForIdentity.credentials().secretKey().getBytes(UTF_8))
.withSessionToken( credentialsForIdentity.credentials().sessionToken().getBytes(UTF_8))
.build())
.build();
}
}
and then when I’m trying to connect I’m getting previously mentioned error:
MqttClientConnection connection) throws ExecutionException, InterruptedException {
try (connection) {
CompletableFuture<Boolean> connected = connection.connect();
boolean sessionPresent = connected.get(); // <--- here!
}
}