Skip to content

Commit 8d458bf

Browse files
Add Cognito connect sample (#333)
1 parent a451e04 commit 8d458bf

File tree

7 files changed

+265
-1
lines changed

7 files changed

+265
-1
lines changed

Diff for: .github/workflows/ci.yml

+9
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ env:
2020
DA_SHADOW_VALUE_DEFAULT: OFF
2121
CI_IOT_CONTAINERS: ${{ secrets.AWS_CI_IOT_CONTAINERS }}
2222
CI_PUBSUB_ROLE: ${{ secrets.AWS_CI_PUBSUB_ROLE }}
23+
CI_COGNITO_ROLE: ${{ secrets.AWS_CI_COGNITO_ROLE }}
2324
CI_CUSTOM_AUTHORIZER_ROLE: ${{ secrets.AWS_CI_CUSTOM_AUTHORIZER_ROLE }}
2425
CI_SHADOW_ROLE: ${{ secrets.AWS_CI_SHADOW_ROLE }}
2526
CI_JOBS_ROLE: ${{ secrets.AWS_CI_JOBS_ROLE }}
@@ -203,6 +204,14 @@ jobs:
203204
export SOFTHSM2_CONF=/tmp/softhsm2.conf
204205
echo "directories.tokendir = /tmp/tokens" > /tmp/softhsm2.conf
205206
python3 ./aws-iot-device-sdk-js-v2/utils/run_sample_ci.py --file ./aws-iot-device-sdk-js-v2/.github/workflows/ci_run_pkcs11_connect_cfg.json
207+
- name: configure AWS credentials (Cognito)
208+
uses: aws-actions/configure-aws-credentials@v1
209+
with:
210+
role-to-assume: ${{ env.CI_COGNITO_ROLE }}
211+
aws-region: ${{ env.AWS_DEFAULT_REGION }}
212+
- name: run Cognito Connect sample
213+
run: |
214+
python3 ./aws-iot-device-sdk-js-v2/utils/run_sample_ci.py --file ./aws-iot-device-sdk-js-v2/.github/workflows/ci_run_cognito_connect_cfg.json
206215
- name: configure AWS credentials (Custom Authorizer)
207216
uses: aws-actions/configure-aws-credentials@v1
208217
with:

Diff for: .github/workflows/ci_run_cognito_connect_cfg.json

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"language": "Javascript",
3+
"sample_file": "./aws-iot-device-sdk-js-v2/samples/node/cognito_connect",
4+
"sample_region": "us-east-1",
5+
"sample_main_class": "",
6+
"arguments": [
7+
{
8+
"name": "--endpoint",
9+
"secret": "ci/endpoint"
10+
},
11+
{
12+
"name": "--signing_region",
13+
"data": "us-east-1"
14+
},
15+
{
16+
"name": "--cognito_identity",
17+
"secret": "ci/Cognito/identity_id"
18+
}
19+
]
20+
}

Diff for: samples/README.md

+54
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
* [Windows Cert Connect](#node-windows-cert-connect)
1010
* [Custom Authorizer Connect](#node-custom-authorizer-connect)
1111
* [Browser: Custom Authorizer Connect](#browser-custom-authorizer-connect)
12+
* [Cognito Connect](#node-cognito-connect)
13+
* [Browser: Cognito Connect](#browser-cognito-connect)
1214
* [Shadow](#node-shadow)
1315
* [Fleet Provisioning](#fleet-provisioning)
1416
* [Jobs](#jobs)
@@ -409,6 +411,58 @@ To run the sample:
409411
* Run `npm install` in the `browser/custom_authorizer_connect` folder
410412
* Open `browser/custom_authorizer_connect/index.html` from your browser
411413
414+
## Node: Cognito Connect
415+
416+
This sample makes an MQTT websocket connection and connects through a [Cognito](https://aws.amazon.com/cognito/) identity. On startup, the device connects to the server and then disconnects. This sample is for reference on connecting using Cognito.
417+
418+
To run this sample, you need to have a Cognito identifier ID. You can get a Cognito identifier ID by creating a Cognito identity pool. For creating Cognito identity pools, please see the following page on the AWS documentation: [Tutorial: Creating an identity pool](https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-identity-pool.html)
419+
420+
**Note:** This sample assumes using an identity pool with unauthenticated identity access for the sake of convenience. Please follow best practices in a real world application based on the needs of your application and the intended use case.
421+
422+
Once you have a Cognito identity pool, you can run the following CLI command to get the Cognito identity pool ID:
423+
424+
```sh
425+
aws cognito-identity get-id --identity-pool-id <cognito identity pool id>
426+
# result from above command
427+
{
428+
"IdentityId": "<cognito identity ID>"
429+
}
430+
```
431+
432+
You can then use the returned ID in the `IdentityId` result as the input for the `--cognito_identity` argument. Please note that the Cognito identity pool ID is **not** the same as a Cognito identity ID and the sample will not work if you pass a Cognito pool id.
433+
434+
Your IoT Thing's [Policy](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html) must provide privileges for this sample to connect. 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.
435+
436+
<details>
437+
<summary>(see sample policy)</summary>
438+
<pre>
439+
{
440+
"Version": "2012-10-17",
441+
"Statement": [
442+
{
443+
"Effect": "Allow",
444+
"Action": [
445+
"iot:Connect"
446+
],
447+
"Resource": [
448+
"arn:aws:iot:<b>region</b>:<b>account</b>:client/test-*"
449+
]
450+
}
451+
]
452+
}
453+
</pre>
454+
</details>
455+
456+
Run the sample like this:
457+
``` sh
458+
npm install
459+
node dist/index.js --endpoint <endpoint> --signing_region <signing region> --cognito_identity <cognito identity ID>
460+
```
461+
462+
## Browser: Cognito Connect
463+
464+
See the Browser Pub/Sub sample for an example of how to connect to AWS via Cognito on the browser: [Browser Pub/Sub sample](#browser-pubsub)
465+
412466
## Node: Shadow
413467
414468
This sample uses the AWS IoT

Diff for: samples/node/cognito_connect/index.ts

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/**
2+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
* SPDX-License-Identifier: Apache-2.0.
4+
*/
5+
6+
import { mqtt, iot, http, auth} from 'aws-iot-device-sdk-v2';
7+
type Args = { [index: string]: any };
8+
9+
const yargs = require('yargs');
10+
11+
12+
// The relative path is '../../util/cli_args' from here, but the compiled javascript file gets put one level
13+
// deeper inside the 'dist' folder
14+
const common_args = require('../../../util/cli_args');
15+
16+
yargs.command('*', false, (yargs: any) => {
17+
yargs.usage("Connect using a Cognito identity.");
18+
common_args.add_universal_arguments(yargs);
19+
common_args.add_common_mqtt_arguments(yargs);
20+
common_args.add_common_websocket_arguments(yargs, true);
21+
common_args.add_cognito_arguments(yargs);
22+
common_args.add_proxy_arguments(yargs);
23+
}, main).parse();
24+
25+
// Creates and returns a websocket MQTT connection using Cognito to authenticate
26+
function build_connection(argv: Args): mqtt.MqttClientConnection {
27+
/**
28+
* Note: This sample assumes that you are using a Cognito identity in the same region as you pass to "--signing_region".
29+
* If not, you may need to adjust the Cognito endpoint. See https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html
30+
* for all Cognito region endpoints.
31+
*/
32+
let cognito_endpoint = "cognito-identity." + argv.signing_region + ".amazonaws.com";
33+
34+
let cognito_credentials : iot.WebsocketConfig = {
35+
region: argv.signing_region,
36+
credentials_provider: auth.AwsCredentialsProvider.newCognito({
37+
endpoint: cognito_endpoint,
38+
identity: argv.cognito_identity
39+
})
40+
}
41+
let config_builder = iot.AwsIotMqttConnectionConfigBuilder.new_websocket_builder(cognito_credentials);
42+
43+
if (argv.proxy_host) {
44+
config_builder.with_http_proxy_options(new http.HttpProxyOptions(argv.proxy_host, argv.proxy_port));
45+
}
46+
if (argv.ca_file != null) {
47+
config_builder.with_certificate_authority_from_path(undefined, argv.ca_file);
48+
}
49+
50+
config_builder.with_clean_session(false);
51+
config_builder.with_client_id(argv.client_id || "test-" + Math.floor(Math.random() * 100000000));
52+
config_builder.with_endpoint(argv.endpoint);
53+
const config = config_builder.build();
54+
55+
const client = new mqtt.MqttClient();
56+
return client.new_connection(config);
57+
}
58+
59+
async function main(argv: Args) {
60+
common_args.apply_sample_arguments(argv);
61+
const connection = build_connection(argv);
62+
63+
// force node to wait 20 seconds before killing itself, promises do not keep node alive
64+
// ToDo: we can get rid of this but it requires a refactor of the native connection binding that includes
65+
// pinning the libuv event loop while the connection is active or potentially active.
66+
const timer = setInterval(() => { }, 20 * 1000);
67+
68+
console.log("Connecting...");
69+
await connection.connect()
70+
console.log("Connection completed.");
71+
console.log("Disconnecting...");
72+
await connection.disconnect()
73+
console.log("Disconnect completed.");
74+
75+
// Allow node to die if the promise above resolved
76+
clearTimeout(timer);
77+
}

Diff for: samples/node/cognito_connect/package.json

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"name": "cognito-connect",
3+
"version": "1.0.0",
4+
"description": "NodeJS IoT SDK v2 Cognito Connect Sample",
5+
"homepage": "https://github.com/aws/aws-iot-device-sdk-js-v2",
6+
"repository": {
7+
"type": "git",
8+
"url": "git+https://github.com/aws/aws-iot-device-sdk-js-v2.git"
9+
},
10+
"contributors": [
11+
"AWS SDK Common Runtime Team <[email protected]>"
12+
],
13+
"license": "Apache-2.0",
14+
"main": "./dist/index.js",
15+
"scripts": {
16+
"tsc": "tsc",
17+
"prepare": "npm run tsc"
18+
},
19+
"devDependencies": {
20+
"@types/node": "^10.17.50",
21+
"typescript": "^4.7.4"
22+
},
23+
"dependencies": {
24+
"aws-iot-device-sdk-v2": "file:../../..",
25+
"yargs": "^16.2.0"
26+
}
27+
}

Diff for: samples/node/cognito_connect/tsconfig.json

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
{
2+
"compilerOptions": {
3+
/* Basic Options */
4+
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
5+
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
6+
// "lib": [], /* Specify library files to be included in the compilation. */
7+
// "allowJs": true, /* Allow javascript files to be compiled. */
8+
// "checkJs": true, /* Report errors in .js files. */
9+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
10+
"declaration": true, /* Generates corresponding '.d.ts' file. */
11+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
12+
"sourceMap": true, /* Generates corresponding '.map' file. */
13+
// "outFile": "./", /* Concatenate and emit output to single file. */
14+
"outDir": "./dist", /* Redirect output structure to the directory. */
15+
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
16+
// "composite": true, /* Enable project compilation */
17+
// "removeComments": false, /* Do not emit comments to output. */
18+
// "noEmit": true, /* Do not emit outputs. */
19+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
20+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
21+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
22+
/* Strict Type-Checking Options */
23+
"strict": true, /* Enable all strict type-checking options. */
24+
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
25+
"strictNullChecks": true, /* Enable strict null checks. */
26+
"strictFunctionTypes": true, /* Enable strict checking of function types. */
27+
"strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
28+
"strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
29+
"noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
30+
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
31+
/* Additional Checks */
32+
"noUnusedLocals": true, /* Report errors on unused locals. */
33+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
34+
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
35+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
36+
/* Module Resolution Options */
37+
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
38+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
39+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
40+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
41+
// "typeRoots": [], /* List of folders to include type definitions from. */
42+
// "types": [], /* Type declaration files to be included in compilation. */
43+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
44+
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
45+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
46+
/* Source Map Options */
47+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
48+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
49+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
50+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
51+
/* Experimental Options */
52+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
53+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
54+
},
55+
"include": [
56+
"*.ts"
57+
],
58+
"exclude": [
59+
"node_modules",
60+
"dist"
61+
]
62+
}

Diff for: samples/util/cli_args.js

+16-1
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,20 @@ function add_jobs_arguments(yargs) {
244244
})
245245
}
246246

247+
/*
248+
* Arguments specific to the Cognito samples.
249+
*/
250+
function add_cognito_arguments(yargs) {
251+
yargs
252+
.option('cognito_identity', {
253+
alias: 'i',
254+
description: 'The Cognito identity ID to use to connect via Cognito',
255+
type: 'string',
256+
default: '',
257+
required: true
258+
})
259+
}
260+
247261
/*
248262
* Handles any non-specific arguments that are relevant to all samples
249263
*/
@@ -386,6 +400,7 @@ exports.add_topic_message_arguments = add_topic_message_arguments;
386400
exports.add_shadow_arguments = add_shadow_arguments;
387401
exports.add_custom_authorizer_arguments = add_custom_authorizer_arguments;
388402
exports.add_jobs_arguments = add_jobs_arguments;
403+
exports.add_cognito_arguments = add_cognito_arguments;
389404
exports.apply_sample_arguments = apply_sample_arguments;
390405
exports.build_connection_from_cli_args = build_connection_from_cli_args;
391-
exports.build_mqtt5_client_from_cli_args = build_mqtt5_client_from_cli_args;
406+
exports.build_mqtt5_client_from_cli_args = build_mqtt5_client_from_cli_args;

0 commit comments

Comments
 (0)