Skip to content

Commit 1a0c4bc

Browse files
authored
WebSocket Connection methods (#545)
* WebSocket Connection methods * Merge readmes into one file * Fix local links * Fix local links * Fix local links * add connection_setup to websocket_connect * add return
1 parent 4b69090 commit 1a0c4bc

File tree

3 files changed

+187
-10
lines changed

3 files changed

+187
-10
lines changed

samples/utils/command_line_utils.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,10 @@ class CmdData:
294294
# PKCS12
295295
input_pkcs12_file : str
296296
input_pkcs12_password : str
297+
# Static credentials
298+
input_session_token : str
299+
input_access_key_id : str
300+
input_secret_access_key : str
297301

298302
def __init__(self) -> None:
299303
pass
@@ -424,6 +428,27 @@ def parse_sample_input_custom_authorizer_connect():
424428
cmdData.input_is_ci = cmdUtils.get_command(CommandLineUtils.m_cmd_is_ci, None) != None
425429
return cmdData
426430

431+
def parse_sample_input_static_credentials_connect():
432+
cmdUtils = CommandLineUtils(
433+
"Static Credentials Connect - Make a MQTT connection using Static Credentials.")
434+
cmdUtils.add_common_mqtt_commands()
435+
cmdUtils.add_common_logging_commands()
436+
cmdUtils.register_command(CommandLineUtils.m_cmd_client_id, "<str>",
437+
"Client ID to use for MQTT connection (optional, default='test-*').",
438+
default="test-" + str(uuid4()))
439+
cmdUtils.register_command(CommandLineUtils.m_cmd_session_token, "<str>", "", default="test-" + str(uuid4()))
440+
cmdUtils.register_command(CommandLineUtils.m_cmd_access_key_id, "<int>", "", type=int)
441+
cmdUtils.register_command(CommandLineUtils.m_cmd_secret_access_key, "<str>", "")
442+
cmdUtils.get_args()
443+
444+
cmdData = CommandLineUtils.CmdData()
445+
cmdData.input_endpoint = cmdUtils.get_command_required(CommandLineUtils.m_cmd_endpoint)
446+
cmdData.input_session_token = cmdUtils.get_command(CommandLineUtils.m_cmd_session_token)
447+
cmdData.input_access_key_id = cmdUtils.get_command(CommandLineUtils.m_cmd_access_key_id)
448+
cmdData.input_secret_access_key = cmdUtils.get_command(CommandLineUtils.m_secret_access_key)
449+
cmdData.input_clientId = cmdUtils.get_command(CommandLineUtils.m_cmd_client_id, "test-" + str(uuid4()))
450+
cmdData.input_is_ci = cmdUtils.get_command(CommandLineUtils.m_cmd_is_ci, None) != None
451+
return cmdData
427452

428453
def parse_sample_input_fleet_provisioning():
429454
cmdUtils = CommandLineUtils("Fleet Provisioning - Provision device using either the keys or CSR.")
@@ -892,3 +917,6 @@ def parse_sample_input_pkcs12_connect():
892917
m_cmd_pkcs12_password = "pkcs12_password"
893918
m_cmd_region = "region"
894919
m_cmd_mqtt_version = "mqtt_version"
920+
m_cmd_session_token = "session_token"
921+
m_cmd_secret_access_key = "secret_access_key"
922+
m_cmd_access_key_id = "access_key_id"

samples/websocket_connect.md

Lines changed: 150 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,19 @@
11
# Websocket Connect
22

33
[**Return to main sample list**](./README.md)
4+
If you want to use custom auth (or static creds, or basic auth, etc) instead,
5+
then you will need to replace part of the sample (connection\_setup function) with a code snippet we provided in its corresponding readme.
46

5-
This sample makes an MQTT connection via Websockets and then disconnects. On startup, the device connects to the server via Websockets and then disconnects right after. This sample is for reference on connecting via Websockets. This sample demonstrates the most straightforward way to connect via Websockets by querying the AWS credentials for the connection from the device's environment variables or local files.
7+
* [Websocket Connection Using Custom Authentication](#websocket-connection-using-custom-authentication)
8+
* [Websocket Connection Using Static Credentials](#websocket-connection-using-custom-authentication)
69

7-
Your IoT Core Thing's [Policy](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html) must provide privileges for this sample to connect. Below is a sample policy that can be used on your IoT Core Thing that will allow this sample to run as intended.
10+
This sample makes an MQTT connection via Websockets and then disconnects.
11+
On startup, the device connects to the server via Websockets and then disconnects right after.
12+
This sample is for reference on connecting via Websockets.
13+
This sample demonstrates the most straightforward way to connect via Websockets by querying the AWS credentials for the connection from the device's environment variables or local files.
14+
15+
Your IoT Core Thing's [Policy](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html) must provide privileges for this sample to connect.
16+
Below is a sample policy that can be used on your IoT Core Thing that will allow this sample to run as intended.
817

918
<details>
1019
<summary>(see sample policy)</summary>
@@ -29,17 +38,153 @@ Replace with the following with the data from your AWS account:
2938
* `<region>`: The AWS IoT Core region where you created your AWS IoT Core thing you wish to use with this sample. For example `us-east-1`.
3039
* `<account>`: Your AWS IoT Core account ID. This is the set of numbers in the top right next to your AWS account name when using the AWS IoT Core website.
3140

32-
Note that in a real application, you may want to avoid the use of wildcards in your ClientID or use them selectively. Please follow best practices when working with AWS on production applications using the SDK. Also, for the purposes of this sample, please make sure your policy allows a client ID of `test-*` to connect or use `--client_id <client ID here>` to send the client ID your policy supports.
41+
Note that in a real application, you may want to avoid the use of wildcards in your ClientID or use them selectively.
42+
Please follow best practices when working with AWS on production applications using the SDK.
43+
Also, for the purposes of this sample, please make sure your policy allows a client ID of `test-*` to connect or use `--client_id <client ID here>` to send the client ID your policy supports.
3344

34-
For this sample, using Websockets will attempt to fetch the AWS credentials to authorize the connection from your environment variables or local files. See the [authorizing direct AWS](https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html) page for documentation on how to get the AWS credentials, which then you can set to the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` environment variables.
45+
For this sample, using Websockets will attempt to fetch the AWS credentials to authorize the connection from your environment variables or local files.
46+
See the [authorizing direct AWS](https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html) page for documentation on how to get the AWS credentials, which then you can set to the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` environment variables.
3547

3648
</details>
3749

3850
## How to run
3951

52+
Optional parameters:
53+
```
54+
--proxy_host <str>
55+
--proxy_port <int>
56+
```
4057
To run the websocket connect from the `samples` folder, use the following command:
4158

4259
``` sh
4360
# For Windows: replace 'python3' with 'python' and '/' with '\'
44-
python3 websocket_connect.py --endpoint <endpoint> --signing_region <signing region>
61+
python3 websocket_connect.py --endpoint <endpoint> --signing_region <signing region> --proxy_host <str> --proxy_port <int>
62+
```
63+
64+
65+
# Websocket Connection Using Custom Authentication
66+
67+
This sample makes an MQTT connection and connects through a [Custom Authorizer](https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html).
68+
On startup, the device connects to the server and then disconnects.
69+
This sample is for reference on connecting using a Custom Authorizer.
70+
Using a Custom Authorizer allows you to perform your own authorization using an AWS Lambda function.
71+
See [Custom Authorizer](https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html) for more information.
72+
You will need to setup your Custom Authorizer so that the lambda function returns a policy document.
73+
See [this page on the documentation](https://docs.aws.amazon.com/iot/latest/developerguide/config-custom-auth.html) for more details and example return result.
74+
You can customize this lambda function as needed for your application to provide your own security measures based on the needs of your application.
75+
Your IoT Core Thing's [Policy](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html) must provide privileges for this sample to connect.
76+
Below is a sample policy that can be used on your IoT Core Thing that will allow this sample to run as intended.
77+
78+
If you want to use simple or custom auth (or static creds, or basic auth, etc) instead,
79+
then you will need to replace part of the sample (connection\_setup function) with a code snippet we provided in its corresponding readme.
80+
81+
<details>
82+
<summary> (code snipet to replace the similar function)</summary>
83+
<pre language="python">
84+
<code>
85+
def connection_setup():
86+
# cmdData is the arguments/input from the command line placed into a single struct for
87+
# use in this sample. This handles all of the command line parsing, validating, etc.
88+
# See the Utils/CommandLineUtils for more information.
89+
cmdData = CommandLineUtils.parse_sample_input_custom_authorizer_connect()
90+
# Create the proxy options if the data is present in cmdData
91+
proxy_options = None
92+
93+
if cmdData.input_proxy_host is not None and cmdData.input_proxy_port != 0:
94+
proxy_options = http.HttpProxyOptions(
95+
host_name=cmdData.input_proxy_host,
96+
port=cmdData.input_proxy_port)
97+
98+
# Create a default credentials provider and a MQTT connection from the command line data
99+
credentials_provider = auth.AwsCredentialsProvider.new_default_chain()
100+
101+
mqtt_connection = mqtt_connection_builder.websockets_with_custom_authorizer(
102+
endpoint=cmdData.input_endpoint,
103+
credentials_provider=credentials_provider,
104+
auth_username=cmdData.input_input_custom_auth_username,
105+
auth_authorizer_name=cmdData.input_custom_authorizer_name,
106+
auth_authorizer_signature=cmdData.input_custom_authorizer_signature,
107+
auth_password=cmdData.input_custom_auth_password,
108+
auth_token_key_name=cmdData.input_custom_authorizer_token_key_name,
109+
auth_token_value=cmdData.input_custom_authorizer_token_value,
110+
on_connection_interrupted=on_connection_interrupted,
111+
on_connection_resumed=on_connection_resumed,
112+
client_id=cmdData.input_clientId,
113+
clean_session=False,
114+
keep_alive_secs=30)
115+
116+
return mqtt_connection, cmdData
117+
118+
</code>
119+
</pre>
120+
</details>
121+
122+
## How to run
123+
Options for custom auth
124+
```
125+
--custom_auth_username <str>
126+
--custom_auth_authorizer_name <str>
127+
--custom_auth_authorizer_signature <str>
128+
--custom_auth_password <str>
129+
--custom_auth_token_name <str>
130+
--custom_auth_token_value <str>
45131
```
132+
133+
To run the websocket connect from the `samples` folder, use the following command:
134+
``` sh
135+
# For Windows: replace 'python3' with 'python' and '/' with '\'
136+
python3 websocket_connect.py --endpoint <endpoint> --custom_auth_username <str> --custom_auth_authorizer_name <str> --custom_auth_authorizer_signature <str> --custom_auth_password <str> --custom_auth_token_name <str> --custom_auth_token_value <str>
137+
```
138+
139+
140+
# Websocket Connection Using Static Credentials
141+
This sample makes an MQTT connection via Websockets and then disconnects.
142+
On startup, the device connects to the server via Websockets then disconnects right after.
143+
This sample demonstrates connecting via static credentials.
144+
145+
If you want to use simple or custom auth (or static creds, or basic auth, etc) instead,
146+
then you will need to replace part of the sample (connection\_setup function) with a code snippet we provided in its corresponding readme.
147+
148+
For this sample, using Websockets will attempt to fetch the AWS credentials to authorize the connection from static credentials.
149+
150+
<details>
151+
<summary> (code snipet to replace the similar function)</summary>
152+
<pre language=cpp>
153+
<code >
154+
def connection_setup():
155+
# cmdData is the arguments/input from the command line placed into a single struct for
156+
# use in this sample. This handles all of the command line parsing, validating, etc.
157+
# See the Utils/CommandLineUtils for more information.
158+
cmdData = CommandLineUtils.parse_sample_input_static_credentials_connect()
159+
160+
cred_provider = AwsCredentialsProvider.new_static(
161+
access_key_id=cmdData.input_access_key_id,
162+
secret_access_key=cmdData.input_secret_access_key,
163+
session_token=cmdData.input_session_token)
164+
165+
mqtt_connection = mqtt_connection_builder.websockets_with_default_aws_signing(
166+
region=cmdData.input_signing_region,
167+
credentials_provider=cred_provider,
168+
endpoint=cmdData.input_endpoint,
169+
client_id=cmdData.input_clientId)
170+
171+
return mqtt_connection, cmdData
172+
</code>
173+
</pre>
174+
</details>
175+
176+
## How to run
177+
178+
Options for static credentials
179+
```
180+
--access_key_id <str>
181+
--secret_access_key <str>
182+
--session_token <str>
183+
```
184+
185+
To run the websocket connect from the `samples` folder, use the following command:
186+
``` sh
187+
# For Windows: replace 'python3' with 'python' and '/' with '\'
188+
python3 websocket_connect.py --endpoint <endpoint> --signing_region <signing region> --access_key_id <str> --secret_access_key <str> --session_token <str>
189+
```
190+

samples/websocket_connect.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,6 @@
88
# This sample shows how to create a MQTT connection using websockets.
99
# This sample is intended to be used as a reference for making MQTT connections.
1010

11-
# cmdData is the arguments/input from the command line placed into a single struct for
12-
# use in this sample. This handles all of the command line parsing, validating, etc.
13-
# See the Utils/CommandLineUtils for more information.
14-
cmdData = CommandLineUtils.parse_sample_input_websocket_connect()
1511

1612
# Callback when connection is accidentally lost.
1713
def on_connection_interrupted(connection, error, **kwargs):
@@ -21,8 +17,12 @@ def on_connection_interrupted(connection, error, **kwargs):
2117
def on_connection_resumed(connection, return_code, session_present, **kwargs):
2218
print("Connection resumed. return_code: {} session_present: {}".format(return_code, session_present))
2319

20+
def connection_setup():
21+
# cmdData is the arguments/input from the command line placed into a single struct for
22+
# use in this sample. This handles all of the command line parsing, validating, etc.
23+
# See the Utils/CommandLineUtils for more information.
24+
cmdData = CommandLineUtils.parse_sample_input_websocket_connect()
2425

25-
if __name__ == '__main__':
2626
# Create the proxy options if the data is present in cmdData
2727
proxy_options = None
2828
if cmdData.input_proxy_host is not None and cmdData.input_proxy_port != 0:
@@ -42,6 +42,10 @@ def on_connection_resumed(connection, return_code, session_present, **kwargs):
4242
client_id=cmdData.input_clientId,
4343
clean_session=False,
4444
keep_alive_secs=30)
45+
return mqtt_connection, cmdData
46+
47+
if __name__ == '__main__':
48+
mqtt_connection, cmdData = connection_setup()
4549

4650
if not cmdData.input_is_ci:
4751
print(f"Connecting to {cmdData.input_endpoint} with client ID '{cmdData.input_clientId}'...")

0 commit comments

Comments
 (0)