banner



How To Use Aws Access Key And Secret Key In Node Js App

New Version Available

A new AWS IoT Device SDK is now available. It is a complete rework, built to improve reliability, performance, and security. We invite your feedback!

This SDK will no longer receive feature updates, but will receive security updates.

AWS IoT SDK for JavaScript

The aws-iot-device-sdk.js package allows developers to write JavaScript applications which access the AWS IoT Platform via MQTT or MQTT over the Secure WebSocket Protocol. It can be used in Node.js environments as well as in browser applications.

  • Overview
  • Installation
  • Mac-Only TLS Behavior
  • Examples
  • API Documentation
  • Connection Types
  • Example Programs
  • Browser Applications
  • Troubleshooting
  • Unit Tests
  • License
  • Support

Overview

This document provides instructions on how to install and configure the AWS IoT device SDK for JavaScript, and includes examples demonstrating use of the SDK APIs.

MQTT Connection

This package is built on top of mqtt.js and provides three classes: 'device', 'thingShadow' and 'jobs'. The 'device' class wraps mqtt.js to provide a secure connection to the AWS IoT platform and expose the mqtt.js interfaces upward. It provides features to simplify handling of intermittent connections, including progressive backoff retries, automatic re-subscription upon connection, and queued offline publishing with configurable drain rate.

Collection of Metrics

Beginning with Release v2.2.0 of the SDK, AWS collects usage metrics indicating which language and version of the SDK is being used. This allows us to prioritize our resources towards addressing issues faster in SDKs that see the most and is an important data point. However, we do understand that not all customers would want to report this data by default. In that case, the sending of usage metrics can be easily disabled by set options.enableMetrics to false.

Thing Shadows

The 'thingShadow' class implements additional functionality for accessing Thing Shadows via the AWS IoT API; the thingShadow class allows devices to update, be notified of changes to, get the current state of, or delete Thing Shadows from AWS IoT. Thing Shadows allow applications and devices to synchronize their state on the AWS IoT platform. For example, a remote device can update its Thing Shadow in AWS IoT, allowing a user to view the device's last reported state via a mobile app. The user can also update the device's Thing Shadow in AWS IoT and the remote device will synchronize with the new state. The 'thingShadow' class supports multiple Thing Shadows per mqtt connection and allows pass-through of non-Thing-Shadow topics and mqtt events.

Jobs

The 'jobs' class implements functionality to interact with the AWS IoT Jobs service. The IoT Job service manages deployment of IoT fleet wide tasks such as device software/firmware deployments and updates, rotation of security certificates, device reboots, and custom device specific management tasks.

Included in this package is an example 'agent'. The agent can be used either as a stand-alone program to manage installation and maintenance of files and other running processes or it can be incorporated into a customized agent to meet specific application needs.

Installation

NOTE: AWS IoT Node.js SDK will only support Node version 4 or above.

You can check your node version by

Installing with npm:

npm install aws-iot-device-sdk

Installing from github:

git clone https://github.com/aws/aws-iot-device-sdk-js.git              cd              aws-iot-device-sdk-js npm install

Mac-Only TLS Behavior

Please note that on Mac, once a private key is used with a certificate, that certificate-key pair is imported into the Mac Keychain. All subsequent uses of that certificate will use the stored private key and ignore anything passed in programmatically.

Examples

Device Class

              // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.              // SPDX-License-Identifier: MIT-0              var              awsIot              =              require              (              'aws-iot-device-sdk'              )              ;              //              // Replace the values of '<YourUniqueClientIdentifier>' and '<YourCustomEndpoint>'              // with a unique client identifier and custom host endpoint provided in AWS IoT.              // NOTE: client identifiers must be unique within your AWS account; if a client attempts              // to connect with a client identifier which is already in use, the existing              // connection will be terminated.              //              var              device              =              awsIot              .              device              (              {              keyPath:              <              YourPrivateKeyPath              >,   certPath:              <              YourCertificatePath              >,     caPath:              <              YourRootCACertificatePath              >,   clientId:              <              YourUniqueClientIdentifier              >,       host:              <              YourCustomEndpoint              >              }              )              ;              //              // Device is an instance returned by mqtt.Client(), see mqtt.js for full              // documentation.              //              device              .              on              (              'connect'              ,              function              (              )              {              console              .              log              (              'connect'              )              ;              device              .              subscribe              (              'topic_1'              )              ;              device              .              publish              (              'topic_2'              ,              JSON              .              stringify              (              {              test_data:              1              }              )              )              ;              }              )              ;              device              .              on              (              'message'              ,              function              (              topic              ,              payload              )              {              console              .              log              (              'message'              ,              topic              ,              payload              .              toString              (              )              )              ;              }              )              ;            

Thing Shadow Class

              // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.              // SPDX-License-Identifier: MIT-0              var              awsIot              =              require              (              'aws-iot-device-sdk'              )              ;              //              // Replace the values of '<YourUniqueClientIdentifier>' and '<YourCustomEndpoint>'              // with a unique client identifier and custom host endpoint provided in AWS IoT cloud              // NOTE: client identifiers must be unique within your AWS account; if a client attempts              // to connect with a client identifier which is already in use, the existing              // connection will be terminated.              //              var              thingShadows              =              awsIot              .              thingShadow              (              {              keyPath:              <              YourPrivateKeyPath              >,   certPath:              <              YourCertificatePath              >,     caPath:              <              YourRootCACertificatePath              >,   clientId:              <              YourUniqueClientIdentifier              >,       host:              <              YourCustomEndpoint              >              }              )              ;              //              // Client token value returned from thingShadows.update() operation              //              var              clientTokenUpdate              ;              //              // Simulated device values              //              var              rval              =              187              ;              var              gval              =              114              ;              var              bval              =              222              ;              thingShadows              .              on              (              'connect'              ,              function              (              )              {              //              // After connecting to the AWS IoT platform, register interest in the              // Thing Shadow named 'RGBLedLamp'.              //              thingShadows              .              register              (              'RGBLedLamp'              ,              {              }              ,              function              (              )              {              // Once registration is complete, update the Thing Shadow named              // 'RGBLedLamp' with the latest device state and save the clientToken              // so that we can correlate it with status or timeout events.              //              // Thing shadow state              //              var              rgbLedLampState              =              {              "state":{              "desired":{              "red":rval              ,              "green":gval              ,              "blue":bval              }              }              }              ;              clientTokenUpdate              =              thingShadows              .              update              (              'RGBLedLamp'              ,              rgbLedLampState              )              ;              //              // The update method returns a clientToken; if non-null, this value will              // be sent in a 'status' event when the operation completes, allowing you              // to know whether or not the update was successful.  If the update method              // returns null, it's because another operation is currently in progress and              // you'll need to wait until it completes (or times out) before updating the              // shadow.              //              if              (              clientTokenUpdate              ===              null              )              {              console              .              log              (              'update shadow failed, operation still in progress'              )              ;              }              }              )              ;              }              )              ;              thingShadows              .              on              (              'status'              ,              function              (              thingName              ,              stat              ,              clientToken              ,              stateObject              )              {              console              .              log              (              'received '              +              stat              +              ' on '              +              thingName              +              ': '              +              JSON              .              stringify              (              stateObject              )              )              ;              //              // These events report the status of update(), get(), and delete()              // calls.  The clientToken value associated with the event will have              // the same value which was returned in an earlier call to get(),              // update(), or delete().  Use status events to keep track of the              // status of shadow operations.              //              }              )              ;              thingShadows              .              on              (              'delta'              ,              function              (              thingName              ,              stateObject              )              {              console              .              log              (              'received delta on '              +              thingName              +              ': '              +              JSON              .              stringify              (              stateObject              )              )              ;              }              )              ;              thingShadows              .              on              (              'timeout'              ,              function              (              thingName              ,              clientToken              )              {              console              .              log              (              'received timeout on '              +              thingName              +              ' with token: '              +              clientToken              )              ;              //              // In the event that a shadow operation times out, you'll receive              // one of these events.  The clientToken value associated with the              // event will have the same value which was returned in an earlier              // call to get(), update(), or delete().              //              }              )              ;            

Jobs Class

              // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.              // SPDX-License-Identifier: MIT-0              var              awsIot              =              require              (              'aws-iot-device-sdk'              )              ;              //              // Replace the values of '<YourUniqueClientIdentifier>' and '<YourCustomEndpoint>'              // with a unique client identifier and custom host endpoint provided in AWS IoT cloud              // NOTE: client identifiers must be unique within your AWS account; if a client attempts              // to connect with a client identifier which is already in use, the existing              // connection will be terminated.              //              var              jobs              =              awsIot              .              jobs              (              {              keyPath:              <              YourPrivateKeyPath              >,   certPath:              <              YourCertificatePath              >,     caPath:              <              YourRootCACertificatePath              >,   clientId:              <              YourUniqueClientIdentifier              >,       host:              <              YourCustomEndpoint              >              }              )              ;              //              // Jobs is built on top of awsIot.device and inherits all of the same functionality.              //              jobs              .              on              (              'connect'              ,              function              (              )              {              console              .              log              (              'connect'              )              ;              device              .              subscribe              (              'topic_1'              )              ;              device              .              publish              (              'topic_2'              ,              JSON              .              stringify              (              {              test_data:              1              }              )              )              ;              }              )              ;              jobs              .              on              (              'message'              ,              function              (              topic              ,              payload              )              {              console              .              log              (              'message'              ,              topic              ,              payload              .              toString              (              )              )              ;              }              )              ;              //              // To subscribe to job execution events call the subscribeToJobs method which takes              // a callback that will be invoked when a job execution is available or an error              // occurs. The job object passed to the callback contains information about the job              // execution and methods for updating the job execution status. Details covered              // in the API documentation below.              //              jobs              .              subscribeToJobs              (              thingName              ,              function              (              err              ,              job              )              {              if              (              isUndefined              (              err              )              )              {              console              .              log              (              'default job handler invoked, jobId: '              +              job              .              id              .              toString              (              )              )              ;              console              .              log              (              'job document: '              +              job              .              document              )              ;              }              else              {              console              .              error              (              err              )              ;              }              }              )              ;              jobs              .              subscribeToJobs              (              thingName              ,              'customJob'              ,              function              (              err              ,              job              )              {              if              (              isUndefined              (              err              )              )              {              console              .              log              (              'customJob operation handler invoked, jobId: '              +              job              .              id              .              toString              (              )              )              ;              console              .              log              (              'job document: '              +              job              .              document              )              ;              }              else              {              console              .              error              (              err              )              ;              }              }              )              ;              //              // After calling subscribeToJobs for each operation on a particular thing call              // startJobNotifications to cause any existing queued job executions for the given              // thing to be published to the appropriate subscribeToJobs handler. Only needs              // to be called once per thing.              //              jobs              .              startJobNotifications              (              thingName              ,              function              (              err              )              {              if              (              isUndefined              (              err              )              )              {              console              .              log              (              'job notifications initiated for thing: '              +              thingName              )              ;              }              else              {              console              .              error              (              err              )              ;              }              }              )              ;            

API Documentation

  • awsIot.device()
  • awsIot.thingShadow()
  • awsIot.jobs()
  • awsIot.thingShadow#register()
  • awsIot.thingShadow#unregister()
  • awsIot.thingShadow#update()
  • awsIot.thingShadow#get()
  • awsIot.thingShadow#delete()
  • awsIot.thingShadow#publish()
  • awsIot.thingShadow#subscribe()
  • awsIot.thingShadow#unsubscribe()
  • awsIot.thingShadow#end()
  • awsIot.jobs#subscribeToJobs()
  • awsIot.jobs#unsubscribeFromJobs()
  • awsIot.jobs#startJobNotifications()
  • job
  • job#document
  • job#id
  • job#operation
  • job#status
  • job#inProgress()
  • job#failed()
  • job#succeeded()

awsIot.device(options)

Returns a wrapper for the mqtt.Client() class, configured for a TLS connection with the AWS IoT platform and with arguments as specified in options. The AWSIoT-specific arguments are as follows:

  • host: the AWS IoT endpoint you will use to connect
  • clientId: the client ID you will use to connect to AWS IoT
  • certPath: path of the client certificate file
  • keyPath: path of the private key file associated with the client certificate
  • caPath: path of your CA certificate file
  • clientCert: same as certPath, but can also accept a buffer containing client certificate data
  • privateKey: same as keyPath, but can also accept a buffer containing private key data
  • caCert: same as caPath, but can also accept a buffer containing CA certificate data
  • autoResubscribe: set to 'true' to automatically re-subscribe to topics after reconnection (default 'true')
  • offlineQueueing: set to 'true' to automatically queue published messages while offline (default 'true')
  • offlineQueueMaxSize: enforce a maximum size for the offline message queue (default 0, e.g. no maximum)
  • offlineQueueDropBehavior: set to 'oldest' or 'newest' to define drop behavior on a full queue when offlineQueueMaxSize > 0
  • drainTimeMs: the minimum time in milliseconds between publishes when draining after reconnection (default 250)
  • baseReconnectTimeMs: the base reconnection time in milliseconds (default 1000)
  • maximumReconnectTimeMs: the maximum reconnection time in milliseconds (default 128000)
  • minimumConnectionTimeMs: the minimum time in milliseconds that a connection must be maintained in order to be considered stable (default 20000)
  • protocol: the connection type, either 'mqtts' (default), 'wss' (WebSocket/TLS), or 'wss-custom-auth' (WebSocket/TLS with custom authentication). Note that when set to 'wss', values must be provided for the Access Key ID and Secret Key in either the following options or in environment variables as specified in WebSocket Configuration. When set to 'wss-custom-auth', valid headers must be provided as specified in Custom Auth
  • websocketOptions: if protocol is set to 'wss', you can use this parameter to pass additional options to the underlying WebSocket object; these options are documented here.
  • filename: used to load credentials from the file different than the default location when protocol is set to 'wss'. Default value is '~/.aws/credentials'
  • profile: used to specify which credential profile to be used when protocol is set to 'wss'. Default value is 'default'
  • accessKeyId: used to specify the Access Key ID when protocol is set to 'wss'. Overrides the environment variable AWS_ACCESS_KEY_ID and AWS_ACCESS_KEY_ID from filename if set.
  • secretKey: used to specify the Secret Key when protocol is set to 'wss'. Overrides the environment variable AWS_SECRET_ACCESS_KEYand AWS_SECRET_ACCESS_KEY from filename if set.
  • sessionToken: (required when authenticating via Cognito, optional otherwise) used to specify the Session Token when protocol is set to 'wss'. Overrides the environment variable AWS_SESSION_TOKEN if set.
  • region: used to specify AWS account region (e.g. 'us-east-1') when protocol is set to wss. If undefined, a value is derived from host.
  • customAuthHeaders: used to specify your custom authorization headers when protocol is set to 'wss-custom-auth'. The fields 'X-Amz-CustomAuthorizer-Name', 'X-Amz-CustomAuthorizer-Signature', and the field for your token name are required.
  • servername: used for SNI. If undefined, a value is derived from host.
  • port: used to specify which port to connect to. If undefined, 443 or 8883 will be chosen depending on protocol.
  • customAuthQueryString: used to specify the token credentials in a query string for custom authorization when protocol is set to wss-custom-auth. More info can be found here.
  • keepalive: used to specify the time interval for each ping request. Default is set to 300 seconds to connect to AWS IoT.
  • enableMetrics: used to report SDK version usage metrics. It is set to true by default. To disable metrics collection, set value to false.
  • debug: set to 'true' for verbose logging (default 'false').

All certificates and keys must be in PEM format.

options also contains arguments specific to mqtt. See [the mqtt client documentation] (https://github.com/mqttjs/MQTT.js/blob/master/README.md#client) for details of these arguments. Note, AWS IoT doesn't support retained messages; setting retain flag to 'true' for message publishing, including Last Will and Testament messages, will result in connection termination. For AWS IoT protocol specifics, please visit here.

Supports all events emitted by the mqtt.Client() class.

awsIot.device#updateWebSocketCredentials(accessKeyId, secretKey, sessionToken, expiration)

Update the credentials set used to authenticate via WebSocket/SigV4. This method is designed to be invoked during the callback of the getCredentialsForIdentity method in the AWS SDK for JavaScript.

  • accessKeyId: the latest Access Key to use when connecting via WebSocket/SigV4
  • secretKey: the latest Secret Key to use when connecting via WebSocket/SigV4
  • sessionToken: the latest Session Token to use when connecting via WebSocket/SigV4
  • expiration: the time this credentials set will expire

awsIot.thingShadow(deviceOptions, thingShadowOptions)

The thingShadow class wraps an instance of the device class with additional functionality to operate on Thing Shadows via the AWS IoT API. The arguments in deviceOptions include all those in the device class. thingShadowOptions has the addition of the following arguments specific to the thingShadow class:

  • operationTimeout: the timeout for thing operations (default 10 seconds)

Supports all events emitted by the mqtt.Client() class; however, the semantics for the message event are slightly different and additional events are available as described below:

Event 'message'

function(topic, message) {}

Emitted when a message is received on a topic not related to any Thing Shadows:

  • topic topic of the received packet
  • message payload of the received packet

Event 'status'

function(thingName, stat, clientToken, stateObject) {}

Emitted when an operation update|get|delete completes.

  • thingName name of the Thing Shadow for which the operation has completed
  • stat status of the operation accepted|rejected
  • clientToken the operation's clientToken
  • stateObject the stateObject returned for the operation

Applications can use clientToken values to correlate status events with the operations that they are associated with by saving the clientTokens returned from each operation.

Event 'delta'

function(thingName, stateObject) {}

Emitted when a delta has been received for a registered Thing Shadow.

  • thingName name of the Thing Shadow that has received a delta
  • stateObject the stateObject returned for the operation

Event 'foreignStateChange'

function(thingName, operation, stateObject) {}

Emitted when a different client's update or delete operation is accepted on the shadow.

  • thingName name of the Thing Shadow for which the operation has completed
  • operation operation performed by the foreign client update|delete
  • stateObject the stateObject returned for the operation

This event allows an application to be aware of successful update or delete operations performed by different clients.

Event 'timeout'

function(thingName, clientToken) {}

Emitted when an operation update|get|delete has timed out.

  • thingName name of the Thing Shadow that has received a timeout
  • clientToken the operation's clientToken

Applications can use clientToken values to correlate timeout events with the operations that they are associated with by saving the clientTokens returned from each operation.


awsIot.thingShadow#register(thingName, [options], [callback] )

Register interest in the Thing Shadow named thingName. The thingShadow class will subscribe to any applicable topics, and will fire events for the Thing Shadow until awsIot.thingShadow#unregister() is called with thingName. options can contain the following arguments to modify how this Thing Shadow is processed:

  • ignoreDeltas: set to true to not subscribe to the delta sub-topic for this Thing Shadow; used in cases where the application is not interested in changes (e.g. update only.) (default false)
  • persistentSubscribe: set to false to unsubscribe from all operation sub-topics while not performing an operation (default true)
  • discardStale: set to false to allow receiving messages with old version numbers (default true)
  • enableVersioning: set to true to send version numbers with shadow updates (default true)

The persistentSubscribe argument allows an application to get faster operation responses at the expense of potentially receiving more irrelevant response traffic (i.e., response traffic for other clients who have registered interest in the same Thing Shadow). When persistentSubscribe is set to false, operation sub-topics are only subscribed to during the scope of that operation; note that in this mode, update, get, and delete operations will be much slower; however, the application will be less likely to receive irrelevant response traffic.

The discardStale argument allows applications to receive messages which have obsolete version numbers. This can happen when messages are received out-of-order; applications which set this argument to false should use other methods to determine how to treat the data (e.g. use a time stamp property to know how old/stale it is).

If enableVersioning is set to true, version numbers will be sent with each operation. AWS IoT maintains version numbers for each shadow, and will reject operations which contain the incorrect version; in applications where multiple clients update the same shadow, clients can use versioning to avoid overwriting each other's changes.

If the callback parameter is provided, it will be invoked after registration is complete (i.e., when subscription ACKs have been received for all shadow topics). Applications should wait until shadow registration is complete before performing update/get/delete operations.


awsIot.thingShadow#unregister(thingName)

Unregister interest in the Thing Shadow named thingName. The thingShadow class will unsubscribe from all applicable topics and no more events will be fired for thingName.


awsIot.thingShadow#update(thingName, stateObject)

Update the Thing Shadow named thingName with the state specified in the JavaScript object stateObject. thingName must have been previously registered using awsIot.thingShadow#register(). The thingShadow class will subscribe to all applicable topics and publish stateObject on the update sub-topic.

This function returns a clientToken, which is a unique value associated with the update operation. When a 'status' or 'timeout' event is emitted, the clientToken will be supplied as one of the parameters, allowing the application to keep track of the status of each operation. The caller may create their own clientToken value; if stateObject contains a clientToken property, that will be used rather than the internally generated value. Note that it should be of atomic type (i.e. numeric or string). This function returns 'null' if an operation is already in progress.


awsIot.thingShadow#get(thingName, [clientToken])

Get the current state of the Thing Shadow named thingName, which must have been previously registered using awsIot.thingShadow#register(). The thingShadow class will subscribe to all applicable topics and publish on the get sub-topic.

This function returns a clientToken, which is a unique value associated with the get operation. When a 'status or 'timeout' event is emitted, the clientToken will be supplied as one of the parameters, allowing the application to keep track of the status of each operation. The caller may supply their own clientToken value (optional); if supplied, the value of clientToken will be used rather than the internally generated value. Note that this value should be of atomic type (i.e. numeric or string). This function returns 'null' if an operation is already in progress.


awsIot.thingShadow#delete(thingName, [clientToken])

Delete the Thing Shadow named thingName, which must have been previously registered using awsIot.thingShadow#register(). The thingShadow class will subscribe to all applicable topics and publish on the delete sub-topic.

This function returns a clientToken, which is a unique value associated with the delete operation. When a 'status' or 'timeout' event is emitted, the clientToken will be supplied as one of the parameters, allowing the application to keep track of the status of each operation. The caller may supply their own clientToken value (optional); if supplied, the value of clientToken will be used rather than the internally generated value. Note that this value should be of atomic type (i.e. numeric or string). This function returns 'null' if an operation is already in progress.


awsIot.thingShadow#publish(topic, message, [options], [callback])

Identical to the mqtt.Client#publish() method, with the restriction that the topic may not represent a Thing Shadow. This method allows the user to publish messages to topics on the same connection used to access Thing Shadows.


awsIot.thingShadow#subscribe(topic, [options], [callback])

Identical to the mqtt.Client#subscribe() method, with the restriction that the topic may not represent a Thing Shadow. This method allows the user to subscribe to messages from topics on the same connection used to access Thing Shadows.


awsIot.thingShadow#unsubscribe(topic, [callback])

Identical to the mqtt.Client#unsubscribe() method, with the restriction that the topic may not represent a Thing Shadow. This method allows the user to unsubscribe from topics on the same used to access Thing Shadows.


awsIot.thingShadow

0 Response to "How To Use Aws Access Key And Secret Key In Node Js App"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel