Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save scott-stewart/2d7dc6a01d5da4326a7ad8b49d467354 to your computer and use it in GitHub Desktop.
Save scott-stewart/2d7dc6a01d5da4326a7ad8b49d467354 to your computer and use it in GitHub Desktop.
# Generate Presigned URLS for AWS IoT MQTT WebSockets. There are 2 ways to
# connect to AWS IoT; certificates and Sigv4. Certificates are great for real
# things, but not so great for JavaScript. This presign Rails controller
# example, will allow you to make an authorized ajax call from your apps
# JavaScript to this controller's endpoint, and get back a short lived presign
# url to use to open the connection to your AWS IoT endpoint.
# Note: It is assumed your app already has some sort of session based security
# taking place in ApplicationController, which is omitted here for brevity. You
# would not want an unauthenticated request to be able to get presigned url's
# to your AWS IoT endpoint.
# Note 2: As of this Gist creation, the Aws::Sigv4 in SDK version 3 does not
# properly sign url requests with "wss://" protocols. I submitted a pull
# request as part of working out this example. If using this gist before
# Aws::Sigv4 officially supports wss, a patched version can be found here:
# https://github.com/scott-stewart/aws-sdk-ruby. The pull request for tracking
# purposes is here: https://github.com/aws/aws-sdk-ruby/pull/2232
class IotPresignedUrlsController < ApplicationController
before_action :authorize
def show
url = generate_url
render json: { "url": url.to_s }
end
private
def generate_url
signer = Aws::Sigv4::Signer.new(service: 'iotdevicegateway',
region: ENV['AWS_REGION'],
access_key_id: ENV['AWS_ACCESS_KEY_ID'],
secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'])
signer.presign_url(http_method: 'GET',
url: 'wss://' + ENV['AWS_IOT_ENDPOINT_HOST'].to_s + '/mqtt',
expires_in: 900)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment