java 如何将AWS IoT MQTT与AWS Cognito用户池结合使用

k10s72fa  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(149)

我可能听起来很愚蠢,但从几天开始,我一直在努力寻找如何连接到AWS IoT MQTT的解决方案,该解决方案具有基于CognitoIdentityProviderClient的授权流。
我的设置看起来像这样:
1.我有用户池“some-user-pool”
1.我在用户池“some-user-in-user-pool”中有一个用户
1.我的用户池已附加到IoT策略“some-iot-policy”
接下来呢?我的意思是说,我已经知道我可以通过附加到策略的证书连接到mqtt,但我想通过用户使用它。
所以我在一个步骤中,我有最终的RespondToAuthChallengeResponse后,认证流;一切都很顺利,但我不知道现在该怎么办?如何设置AwsIotMqtt5ClientBuilder以使用用户池?
我有一个类似这样的代码

RespondToAuthChallengeResponse response =  cognitoIdentityProviderClient.respondToAuthChallenge(request)

//After this, I have accessToken and idToken

AwsIotMqtt5ClientBuilder builder = AwsIotMqtt5ClientBuilder.newMqttBuilder(hostname)

//here I'm lost on how I can setup mqtt to use the response
vsnjm48y

vsnjm48y1#

如果您已经进行了基本配置,包括AWS SDK并导入必要的库以使其工作。
您需要初始化AWS IoT和Cognito客户端:

String userPoolId = "your-user-pool-id";
String clientId = "your-client-id";
String username = "user-username"; // username you want to authenticate

CognitoCredentialsProvider credentialsProvider = CognitoCredentialsProvider.builder()
        .clientId(clientId)
        .cognitoIdentityProviderClient(yourCognitoClient)
        .build();

Region region = Region.YOUR_REGION; // Replace with your AWS region

IotClient iotClient = IotClient.builder().region(region).build();
IotDataPlaneClient dataPlaneClient = IotDataPlaneClient.builder().region(region).build();

创建新的MQTT客户端:

AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMqttConnectionBuilder("your-iot-endpoint")
        .clientId("your-client-id")
        .credentialsProvider(credentialsProvider)
        .region(region)
        .protocol(AwsIotMqttConnectionBuilder.Protocol.WSS);

确保Cognito用户与IoT策略相关联。下面是一个如何对Cognito用户实施策略的示例:

String policyName = "your-iot-policy-name";

AttachPolicyRequest attachPolicyRequest =
AttachPolicyRequest.builder()
        .policyName(policyName)
        .target(yourCognitoIdentityId) // Replace with your Cognito Identity ID
        .build();
 
iotClient.attachPolicy(attachPolicyRequest);

连接到AWS IoT MQTT:

AwsIotMqttConnection connection = builder.build();
connection.connect();

这只是使用Cognito的AWS IoT的基本连接实现,但它可能会帮助您弄清楚如何做到这一点。:)

相关问题