· 6 years ago · Jun 25, 2019, 09:56 PM
1{
2 "Version": "2012-10-17",
3 "Statement": [
4 {
5 "Effect": "Allow",
6 "Action": [
7 "mobileanalytics:PutEvents",
8 "cognito-sync:*",
9 "cognito-identity:*"
10 ],
11 "Resource": [
12 "*"
13 ]
14 }
15 ]
16}
17
18{
19 "Version": "2012-10-17",
20 "Statement": [
21 {
22 "Sid": "VisualEditor0",
23 "Effect": "Allow",
24 "Action": "iot:*",
25 "Resource": "*"
26 }
27 ]
28}
29
30auth_data = { 'USERNAME':username , 'PASSWORD':password }
31provider_client=boto3.client('cognito-idp', region_name=region)
32resp = provider_client.admin_initiate_auth(UserPoolId=user_pool_id, AuthFlow='ADMIN_NO_SRP_AUTH', AuthParameters=auth_data, ClientId=client_id)
33id_token=resp['AuthenticationResult']['IdToken']
34
35def _get_aws_cognito_temp_credentials(aws_access_key_id=None,aws_secret_access_key=None,
36 region_name='us-west-2',account_id=None,user_pool_id=None,
37 identity_pool_id=None,id_token=None):
38 boto3.setup_default_session(aws_access_key_id=aws_access_key_id,
39 aws_secret_access_key=aws_secret_access_key,
40 region_name = region_name)
41 identity_client = boto3.client('cognito-identity', region_name=region_name)
42 loginkey = "cognito-idp.%s.amazonaws.com/%s" % (region_name,user_pool_id)
43 print("loginkey is %s" % loginkey)
44 loginsdict={
45 loginkey: id_token
46 }
47 identity_response = identity_client.get_id(AccountId=account_id,
48 IdentityPoolId=identity_pool_id,
49 Logins=loginsdict)
50 identity_id = identity_response['IdentityId']
51 #
52 # Get the identity's credentials
53 #
54 credentials_response = identity_client.get_credentials_for_identity(
55 IdentityId=identity_id,
56 Logins=loginsdict)
57 credentials = credentials_response['Credentials']
58 access_key_id = credentials['AccessKeyId']
59 secret_key = credentials['SecretKey']
60 service = 'execute-api'
61 session_token = credentials['SessionToken']
62 expiration = credentials['Expiration']
63 return access_key_id,secret_key,session_token,expiration
64
65myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)
66myAWSIoTMQTTClient.configureEndpoint(host, port)
67myAWSIoTMQTTClient.configureIAMCredentials(temp_access_key_id,
68 temp_secret_key,
69 temp_session_token)
70myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
71myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)
72myAWSIoTMQTTClient.configureDrainingFrequency(2)
73myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)
74myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)
75log.info("create_aws_iot_client", pre_connect=True)
76myAWSIoTMQTTClient.connect()
77log.info("create_aws_iot_client", post_connect=True, myAWSIoTMQTTClient=myAWSIoTMQTTClient)
78
79AWSIoTPythonSDK.exception.AWSIoTExceptions.connectTimeoutException