SlideShare a Scribd company logo
1 of 48
Download to read offline
© 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Dickson Yue, AWS Solutions Architect
9/15/2017
Building Powerful IoT apps with
AWS IoT and Websockets
AWS Startup Day – Hong Kong
Outline
• MQTT recap
• WebSockets: what and why?
• Authentication and Authorization
• Demo + Code
AWS IoT
Publish / Subscribe
Standard Protocol Support
MQTT, HTTP, WebSockets
Long Lived Connections
Receive signals from the cloud
Secure by Default
Connect securely via X509 Certs
and TLS 1.2 Client Mutual Auth
MQTT PubSub Topic Subscriptions
PUBLISH
weather-station/echo-base/temperature
SUBSCRIBE
weather-station/echo-base/temperature
weather-station/echo-base/#
weather-station/+/temperature
Comparing protocols
MQTT
• Lightweight
• Bidirectional
HTTP
• Broad support (browsers)
• Request-reply
Client Server Client Server
AWS IoT protocol comparison
Capability MQTT HTTP
Publish Yes Yes
Subscribe Yes No
WebSockets to the rescue
GET wss://…/mqtt?X-Amz-Signature=…
Connection: Upgrade
Sec-WebSocket-Protocol: mqtt
…
Upgrade?
OK
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
HTTP
WebSockets to the rescue
HTTP
MQTT
SUBSCRIBE
PUBLISH
…
AWS IoT protocol comparison
*Using WebSockets to upgrade HTTP connections to MQTT connections
Capability MQTT HTTP
Publish Yes Yes
Subscribe Yes Yes*
Outline
• MQTT recap
• WebSockets: what and why?
• Authentication and Authorization
• Demo + Code
Securing AWS Resource Access
Authentication vs authorization
Authentication:
Prove your identity
Authorization:
Restrict access
Authentication for devices
Device credentials
• Private key (authenticate the device)
• Certificate (register the device with IoT)
• Root CA cert (authenticate IoT)
Authentication for devices
Administrator
CreateCertificate
Generate CSR
Generate
Private Key
Certificate
Connect through MQTT libary
import paho.mqtt.client as mqtt
def init():
global client
try:
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.clientid = clientid
client.tls_set( "../../certs/root.pem",
certfile="../../certs/grove-cert.pem",
keyfile="../../certs/grove-privateKey.pem",
tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None )
client.connect("data.iot.us-east-1.amazonaws.com", 8883, 10)
client.loop_forever()
except:
print "Mqtt Unexpected error:", sys.exc_info()[0]
HTTP
curl --tlsv1.2
--cacert root.pem --cert pi01-cert.pem --key pi01-privateKey.pem
-X POST -d "{ "serialNumber": "G030JF053216F1BS", "clickType":
"SINGLE", "batteryVoltage": "2000mV" }"
"https://a1omffl4uase1e.iot.us-east-
1.amazonaws.com:8443/topics/iotbutton/virtualButton?qos=1"
AWS IoT protocol comparison
Capability MQTT HTTP
Publish Yes Yes
Subscribe Yes No
Certificate Auth Yes Yes
Sig V4 Auth No Yes
AWS IoT protocol comparison
Capability MQTT HTTP
Publish Yes Yes
Subscribe Yes No
Certificate Auth Yes Yes
Sig V4 Auth No Yes
AWS IoT protocol comparison
Capability MQTT HTTP
Publish Yes Yes
Subscribe Yes Yes*
Certificate Auth Yes Yes
Sig V4 Auth Yes* Yes
*Using WebSockets to upgrade HTTP connections to MQTT connections
Authenticated
• End-users sign in
• Customize user-specific policy
in AWS IoT
• Users cannot access AWS IoT
until IoT policy is attached
Cognito Identities in AWS IoT
Unauthenticated
• No sign-in (anonymous)
• Use IAM role policy and policy
variables to restrict access
• No user-specific policy
in AWS IoT
Unauthenticated end-users
Unauthenticated access for end-users
Amazon
Cognito
Get Credentials
AssumeRole
Connect through JavaScript
var region = c.AWS.region; //'ap-northeast-1'
var iotEndpoint = c.AWS.iotEndpoint;
var identityPoolId = c.AWS.identityPoolId;
AWS.config.region = region;
AWS.config.credentials =
new AWS.CognitoIdentityCredentials({ IdentityPoolId: identityPoolId });
AWS.config.credentials.get(function(){
var signedUrl = getSignedUrl();
initClient(signedUrl);
});
var requestUrl = 'wss://' + host + canonicalUri + '?' + canonicalQuerystring;
//Unauthenticated
Unauthenticated access for end-users
Amazon
Cognito
Get Credentials
AssumeRole
AWS STS
AWS IAM
permissions
role
temporary
security
credentials
Unauthenticated access for end-users
Amazon
Cognito
AWS STS
AWS IAM
permissions
role
WebSocket Connect
temporary
security
credentials
Allowed?
Yes!
User-specific policies
{
"Effect": "Allow",
"Action": ["iot:Publish", "iot:Subscribe"]
"Resource": [
"arn:*:topic/home/123_aws_ave",
"arn:*:topicfilter/home/123_aws_ave"
]
}
{
"Effect": "Allow",
"Action": ["iot:Publish", "iot:Subscribe"]
"Resource": [
"arn:*:topic/home/456_iot_ln",
"arn:*:topicfilter/home/456_iot_ln"
]
}
Policy for Alice, Bob: Policy for Chuck:
Fine-grained access control
SUB home/456_iot_ln
SUB home/123_aws_ave/#
PUB home/123_aws_ave/light_1/on
SUB home/123_aws_ave/#
PUB home/123_aws_ave/door_1/open
Alice
Bob
Chuck
Fine-grained access control
PUB home/123_aws_ave/door_1/open
SUB home/123_aws_ave/#
PUB home/123_aws_ave/light_1/on
SUB home/123_aws_ave/#
PUB home/123_aws_ave/door_1/open
Alice
Bob
Chuck
Policy variables for Cognito users
AWS IAM
PUBLISH foo/us-east-1:abcdef-my-cognito-id
temporary
security
credentials
{
"Effect": "Allow",
"Action": "iot:Publish",
"Resource": [
"arn:*:topic/foo/${cognito-identity.amazonaws.com:sub}"
]
}
Policy variables for Cognito users
{
"Effect": "Allow",
"Action": "iot:Publish",
"Resource": [
"arn:*:topic/foo/${cognito-identity.amazonaws.com:sub}"
]
}
AWS.config.region = 'us-east-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:YOUR_IDENTITY_POOL_ID'
});
AWS.config.credentials.get(function(err)) {
if (err) { return; }
var cognitoId = AWS.config.credentials.identityId;
mqttClient.connect(...);
mqttClient.publish('foo/' + cognitoId);
});
permissions
role
Outline
• MQTT recap
• WebSockets: what and why?
• Authentication and Authorization
• Demo + Code
http://bit.ly/awsiotws
Authentication for end-users
Configuring Cognito with AWS IoT
UnauthenticatedAuthenticated
Authenticated access for end-users
Amazon
Cognito
Get Credentials
temporary
security
credentials
AWS STSAWS IAM
permissions
role
temporary
security
credentials
Connect through JavaScript
var region = c.AWS.region; //'ap-northeast-1'
var iotEndpoint = c.AWS.iotEndpoint;
var identityPoolId = c.AWS.identityPoolId;
AWS.config.region = region;
AWS.config.credentials =
new AWS.CognitoIdentityCredentials(
{ IdentityPoolId: c.AWS.identityPoolId,
Logins: {'graph.facebook.com': fbresponse.authResponse.accessToken }
});
AWS.config.credentials.get(function(){
var signedUrl = getSignedUrl();
initClient(signedUrl);
});
var requestUrl = 'wss://' + host + canonicalUri + '?' + canonicalQuerystring;
//Authenticated
//After fb.login
Connect through JavaScript
function initClient(requestUrl) {
var clientId = String(Math.random()).replace('.', '');
var client = new Paho.MQTT.Client(requestUrl, clientId);
mqttClient = client;
var connectOptions = {
onSuccess: function() {
client.subscribe(topiclightbulb);
client.subscribe(topicgrove);
},
useSSL: true, timeout: 3, mqttVersion: 4,
onFailure: function() { console.error('connect failed'); }
};
client.connect(connectOptions);
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
}
//Subscribe topics
//Subscribe topics
Authenticated access for end-users
Amazon
Cognito
AWS STS
AWS IAM
permissions
role
WebSocket Connect
temporary
security
credentials
Allowed?
Yes!
IoT
topic
IoT
shadow
IoT
policy
Authenticated access for end-users
Amazon
Cognito
AWS STS
AWS IAM
permissions
role
WebSocket Connect
temporary
security
credentials
Allowed?
Yes!
IoT
topic
IoT
shadow
IoT
policy
Create, Attach
Policy for Alice,
Bob, and Chuck
Authenticated
• End-users sign in
• Customize user-specific policy
in AWS IoT
• Users cannot access AWS IoT
until IoT policy is attached
Cognito Identities in AWS IoT
Unauthenticated
• No sign-in (anonymous)
• Use IAM role policy and policy
variables to restrict access
• No user-specific policy
in AWS IoT
Chicken and egg: when to attach the policy?
• Users cannot connect until they have a policy in IoT
• Policy cannot be attached without knowing the user’s
CognitoId
Solution: attach a policy when the user first connects!
On-demand registration
Amazon
Cognito
AWS
Lambda
CONNECT
Access denied
New User
(already
signed in)
Get Credentials
temporary
security
credentials
(no policy for user)
On-demand registration (continued)
Amazon
Cognito
AWS
Lambda
Register()Create, Attach
Policy
New User
IoT
policy
CONNECT
OK!
context.identity.cognitoIdentityId
Lambda Code – Attach Principal Policy
'use strict';
var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var iot = new AWS.Iot();
exports.handler = (event, context, callback) => {
var cognitoid = ‘';
if (typeof context.identity !== 'undefined') {
cognitoid = context.identity.cognitoIdentityId;
var params = {
policyName: 'cognito-user-access', /* required */
principal: cognitoid /* required */
};
iot.attachPrincipalPolicy(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
};
What permissions to attach?
• Start with minimal permissions
• Dynamically generate or attach your policy base on user
Wrapping up
• WebSockets makes IoT interactive
• Authentication for humans is different than devices
• Use Lambda to drive user registration, pairing
• Getting started with the AWS IoT Device SDK is easy
• AWS IoT WebSockets, Rules Engine, Shadow and
Lambda makes server-less applications easy
Thank you!
Dickson Yue

More Related Content

What's hot

Serverless Architecture and Best Practices
Serverless Architecture and Best PracticesServerless Architecture and Best Practices
Serverless Architecture and Best Practices
Amazon Web Services
 
AWS 기반 Kubernetes 정복하기::정영준:: AWS Summit Seoul 2018
AWS 기반 Kubernetes 정복하기::정영준:: AWS Summit Seoul 2018 AWS 기반 Kubernetes 정복하기::정영준:: AWS Summit Seoul 2018
AWS 기반 Kubernetes 정복하기::정영준:: AWS Summit Seoul 2018
Amazon Web Services Korea
 

What's hot (20)

(DEV203) Amazon API Gateway & AWS Lambda to Build Secure APIs
(DEV203) Amazon API Gateway & AWS Lambda to Build Secure APIs(DEV203) Amazon API Gateway & AWS Lambda to Build Secure APIs
(DEV203) Amazon API Gateway & AWS Lambda to Build Secure APIs
 
AWS Elastic Compute Cloud (EC2)
AWS Elastic Compute Cloud (EC2) AWS Elastic Compute Cloud (EC2)
AWS Elastic Compute Cloud (EC2)
 
Deep Dive - CI/CD on AWS
Deep Dive - CI/CD on AWSDeep Dive - CI/CD on AWS
Deep Dive - CI/CD on AWS
 
AWS Black Belt Online Seminar AWS上のJenkins活用方法
AWS Black Belt Online Seminar AWS上のJenkins活用方法AWS Black Belt Online Seminar AWS上のJenkins活用方法
AWS Black Belt Online Seminar AWS上のJenkins活用方法
 
AWS 상의 컨테이너 서비스 소개 ECS, EKS - 이종립 / Principle Enterprise Evangelist @베스핀글로벌
AWS 상의 컨테이너 서비스 소개 ECS, EKS - 이종립 / Principle Enterprise Evangelist @베스핀글로벌AWS 상의 컨테이너 서비스 소개 ECS, EKS - 이종립 / Principle Enterprise Evangelist @베스핀글로벌
AWS 상의 컨테이너 서비스 소개 ECS, EKS - 이종립 / Principle Enterprise Evangelist @베스핀글로벌
 
AWS Black Belt Online Seminar 2017 Auto Scaling
AWS Black Belt Online Seminar 2017 Auto ScalingAWS Black Belt Online Seminar 2017 Auto Scaling
AWS Black Belt Online Seminar 2017 Auto Scaling
 
AWS Power Tools: Advanced AWS CloudFormation and CLI
AWS Power Tools: Advanced AWS CloudFormation and CLIAWS Power Tools: Advanced AWS CloudFormation and CLI
AWS Power Tools: Advanced AWS CloudFormation and CLI
 
Amazon API Gateway
Amazon API GatewayAmazon API Gateway
Amazon API Gateway
 
AWS CloudFormation Masterclass
AWS CloudFormation MasterclassAWS CloudFormation Masterclass
AWS CloudFormation Masterclass
 
AWS EC2
AWS EC2AWS EC2
AWS EC2
 
Black Belt Online Seminar AWS Amazon S3
Black Belt Online Seminar AWS Amazon S3Black Belt Online Seminar AWS Amazon S3
Black Belt Online Seminar AWS Amazon S3
 
Containers on AWS: An Introduction
Containers on AWS: An IntroductionContainers on AWS: An Introduction
Containers on AWS: An Introduction
 
The fundamentals of AWS cloud security - FND209-R - AWS re:Inforce 2019
The fundamentals of AWS cloud security - FND209-R - AWS re:Inforce 2019 The fundamentals of AWS cloud security - FND209-R - AWS re:Inforce 2019
The fundamentals of AWS cloud security - FND209-R - AWS re:Inforce 2019
 
Serverless Architecture and Best Practices
Serverless Architecture and Best PracticesServerless Architecture and Best Practices
Serverless Architecture and Best Practices
 
CI/CD on AWS
CI/CD on AWSCI/CD on AWS
CI/CD on AWS
 
AWS Containers Day.pdf
AWS Containers Day.pdfAWS Containers Day.pdf
AWS Containers Day.pdf
 
AWS 기반 Kubernetes 정복하기::정영준:: AWS Summit Seoul 2018
AWS 기반 Kubernetes 정복하기::정영준:: AWS Summit Seoul 2018 AWS 기반 Kubernetes 정복하기::정영준:: AWS Summit Seoul 2018
AWS 기반 Kubernetes 정복하기::정영준:: AWS Summit Seoul 2018
 
Amazon Simple Workflow Service (SWF)
Amazon Simple Workflow Service (SWF)Amazon Simple Workflow Service (SWF)
Amazon Simple Workflow Service (SWF)
 
AWS ELB
AWS ELBAWS ELB
AWS ELB
 
천만 사용자를 위한 AWS 아키텍처 보안 모범 사례 (윤석찬, 테크에반젤리스트)
천만 사용자를 위한 AWS 아키텍처 보안 모범 사례 (윤석찬, 테크에반젤리스트)천만 사용자를 위한 AWS 아키텍처 보안 모범 사례 (윤석찬, 테크에반젤리스트)
천만 사용자를 위한 AWS 아키텍처 보안 모범 사례 (윤석찬, 테크에반젤리스트)
 

Viewers also liked

Viewers also liked (6)

Building an AI-based service with Rekognition, Polly and Lex
Building an AI-based service with Rekognition, Polly and LexBuilding an AI-based service with Rekognition, Polly and Lex
Building an AI-based service with Rekognition, Polly and Lex
 
Real-time Chat Backend on AWS IoT 20160422
Real-time Chat Backend on AWS IoT 20160422Real-time Chat Backend on AWS IoT 20160422
Real-time Chat Backend on AWS IoT 20160422
 
Real-Time Event Processing
Real-Time Event ProcessingReal-Time Event Processing
Real-Time Event Processing
 
A guide on Aws Security Token Service
A guide on Aws Security Token ServiceA guide on Aws Security Token Service
A guide on Aws Security Token Service
 
CloudFrontで実現するセキュアコンテンツ配信と効果のトラッキング
CloudFrontで実現するセキュアコンテンツ配信と効果のトラッキングCloudFrontで実現するセキュアコンテンツ配信と効果のトラッキング
CloudFrontで実現するセキュアコンテンツ配信と効果のトラッキング
 
AWS Black Belt Tech シリーズ 2015 - AWS IoT
AWS Black Belt Tech シリーズ 2015 - AWS IoTAWS Black Belt Tech シリーズ 2015 - AWS IoT
AWS Black Belt Tech シリーズ 2015 - AWS IoT
 

Similar to Building Powerful IoT Apps with AWS IoT and Websockets

Similar to Building Powerful IoT Apps with AWS IoT and Websockets (20)

Developing Connected Applications with AWS IoT - Technical 301
Developing Connected Applications with AWS IoT - Technical 301Developing Connected Applications with AWS IoT - Technical 301
Developing Connected Applications with AWS IoT - Technical 301
 
Jeremy Cowan's AWS user group presentation "AWS Greengrass & IoT demo"
Jeremy Cowan's AWS user group presentation "AWS Greengrass & IoT demo"Jeremy Cowan's AWS user group presentation "AWS Greengrass & IoT demo"
Jeremy Cowan's AWS user group presentation "AWS Greengrass & IoT demo"
 
Best Practices for IoT Security in the Cloud
Best Practices for IoT Security in the Cloud Best Practices for IoT Security in the Cloud
Best Practices for IoT Security in the Cloud
 
Best Practices with IoT Security - February Online Tech Talks
Best Practices with IoT Security - February Online Tech TalksBest Practices with IoT Security - February Online Tech Talks
Best Practices with IoT Security - February Online Tech Talks
 
3 Easy Steps to Building Large-Scale IoT Architectures
3 Easy Steps to Building Large-Scale IoT Architectures3 Easy Steps to Building Large-Scale IoT Architectures
3 Easy Steps to Building Large-Scale IoT Architectures
 
AWS Innovate: Building an Internet Connected Camera with AWS IoT- Tim Cruse
AWS Innovate: Building an Internet Connected Camera with AWS IoT- Tim CruseAWS Innovate: Building an Internet Connected Camera with AWS IoT- Tim Cruse
AWS Innovate: Building an Internet Connected Camera with AWS IoT- Tim Cruse
 
AWS re:Invent 2016: Understanding IoT Data: How to Leverage Amazon Kinesis in...
AWS re:Invent 2016: Understanding IoT Data: How to Leverage Amazon Kinesis in...AWS re:Invent 2016: Understanding IoT Data: How to Leverage Amazon Kinesis in...
AWS re:Invent 2016: Understanding IoT Data: How to Leverage Amazon Kinesis in...
 
Deep Dive on AWS IoT Core
Deep Dive on AWS IoT CoreDeep Dive on AWS IoT Core
Deep Dive on AWS IoT Core
 
Secure Content Delivery Using Amazon CloudFront
Secure Content Delivery Using Amazon CloudFrontSecure Content Delivery Using Amazon CloudFront
Secure Content Delivery Using Amazon CloudFront
 
AWS NYC Meetup - May 2017 - "AWS IoT and Greengrass"
AWS NYC Meetup - May 2017 - "AWS IoT and Greengrass"AWS NYC Meetup - May 2017 - "AWS IoT and Greengrass"
AWS NYC Meetup - May 2017 - "AWS IoT and Greengrass"
 
In Depth: AWS IAM and VPC
In Depth: AWS IAM and VPCIn Depth: AWS IAM and VPC
In Depth: AWS IAM and VPC
 
The Lifecycle of an AWS IoT Thing
The Lifecycle of an AWS IoT ThingThe Lifecycle of an AWS IoT Thing
The Lifecycle of an AWS IoT Thing
 
Srv204 Getting Started with AWS IoT
Srv204 Getting Started with AWS IoTSrv204 Getting Started with AWS IoT
Srv204 Getting Started with AWS IoT
 
Workshop AWS IoT @ IoT World Paris
Workshop AWS IoT @ IoT World ParisWorkshop AWS IoT @ IoT World Paris
Workshop AWS IoT @ IoT World Paris
 
Serverless Data Processing on AWS - Level 300
Serverless Data Processing on AWS - Level 300Serverless Data Processing on AWS - Level 300
Serverless Data Processing on AWS - Level 300
 
Getting the Most Value from Your Aviatrix Controller & Gateways
Getting the Most Value from Your Aviatrix Controller & GatewaysGetting the Most Value from Your Aviatrix Controller & Gateways
Getting the Most Value from Your Aviatrix Controller & Gateways
 
Secure Content Delivery Using Amazon CloudFront and AWS WAF
Secure Content Delivery Using Amazon CloudFront and AWS WAFSecure Content Delivery Using Amazon CloudFront and AWS WAF
Secure Content Delivery Using Amazon CloudFront and AWS WAF
 
Secure Content Delivery Using Amazon CloudFront and AWS WAF
Secure Content Delivery Using Amazon CloudFront and AWS WAFSecure Content Delivery Using Amazon CloudFront and AWS WAF
Secure Content Delivery Using Amazon CloudFront and AWS WAF
 
Serverless identity management, authentication, and authorization - SDD405-R ...
Serverless identity management, authentication, and authorization - SDD405-R ...Serverless identity management, authentication, and authorization - SDD405-R ...
Serverless identity management, authentication, and authorization - SDD405-R ...
 
Connecting microcontrollers to the cloud using MQTT, BLE, and HTTP
Connecting microcontrollers to the cloud using MQTT, BLE, and HTTPConnecting microcontrollers to the cloud using MQTT, BLE, and HTTP
Connecting microcontrollers to the cloud using MQTT, BLE, and HTTP
 

More from Amazon Web Services

Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWS
Amazon Web Services
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch Deck
Amazon Web Services
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without servers
Amazon Web Services
 
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
Amazon Web Services
 

More from Amazon Web Services (20)

Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
 
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
 
Esegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS FargateEsegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS Fargate
 
Costruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWSCostruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWS
 
Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot
 
Open banking as a service
Open banking as a serviceOpen banking as a service
Open banking as a service
 
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
 
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
 
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows WorkloadsMicrosoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
 
Computer Vision con AWS
Computer Vision con AWSComputer Vision con AWS
Computer Vision con AWS
 
Database Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatareDatabase Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatare
 
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJSCrea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
 
API moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e webAPI moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e web
 
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatareDatabase Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
 
Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWS
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch Deck
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without servers
 
Fundraising Essentials
Fundraising EssentialsFundraising Essentials
Fundraising Essentials
 
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
 
Introduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container ServiceIntroduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container Service
 

Building Powerful IoT Apps with AWS IoT and Websockets

  • 1. © 2017, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Dickson Yue, AWS Solutions Architect 9/15/2017 Building Powerful IoT apps with AWS IoT and Websockets AWS Startup Day – Hong Kong
  • 2. Outline • MQTT recap • WebSockets: what and why? • Authentication and Authorization • Demo + Code
  • 4. Publish / Subscribe Standard Protocol Support MQTT, HTTP, WebSockets Long Lived Connections Receive signals from the cloud Secure by Default Connect securely via X509 Certs and TLS 1.2 Client Mutual Auth
  • 5. MQTT PubSub Topic Subscriptions PUBLISH weather-station/echo-base/temperature SUBSCRIBE weather-station/echo-base/temperature weather-station/echo-base/# weather-station/+/temperature
  • 6. Comparing protocols MQTT • Lightweight • Bidirectional HTTP • Broad support (browsers) • Request-reply Client Server Client Server
  • 7. AWS IoT protocol comparison Capability MQTT HTTP Publish Yes Yes Subscribe Yes No
  • 8. WebSockets to the rescue GET wss://…/mqtt?X-Amz-Signature=… Connection: Upgrade Sec-WebSocket-Protocol: mqtt … Upgrade? OK HTTP/1.1 101 Switching Protocols Connection: Upgrade HTTP
  • 9. WebSockets to the rescue HTTP MQTT SUBSCRIBE PUBLISH …
  • 10. AWS IoT protocol comparison *Using WebSockets to upgrade HTTP connections to MQTT connections Capability MQTT HTTP Publish Yes Yes Subscribe Yes Yes*
  • 11. Outline • MQTT recap • WebSockets: what and why? • Authentication and Authorization • Demo + Code
  • 13. Authentication vs authorization Authentication: Prove your identity Authorization: Restrict access
  • 14. Authentication for devices Device credentials • Private key (authenticate the device) • Certificate (register the device with IoT) • Root CA cert (authenticate IoT)
  • 16. Connect through MQTT libary import paho.mqtt.client as mqtt def init(): global client try: client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.clientid = clientid client.tls_set( "../../certs/root.pem", certfile="../../certs/grove-cert.pem", keyfile="../../certs/grove-privateKey.pem", tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None ) client.connect("data.iot.us-east-1.amazonaws.com", 8883, 10) client.loop_forever() except: print "Mqtt Unexpected error:", sys.exc_info()[0]
  • 17. HTTP curl --tlsv1.2 --cacert root.pem --cert pi01-cert.pem --key pi01-privateKey.pem -X POST -d "{ "serialNumber": "G030JF053216F1BS", "clickType": "SINGLE", "batteryVoltage": "2000mV" }" "https://a1omffl4uase1e.iot.us-east- 1.amazonaws.com:8443/topics/iotbutton/virtualButton?qos=1"
  • 18. AWS IoT protocol comparison Capability MQTT HTTP Publish Yes Yes Subscribe Yes No Certificate Auth Yes Yes Sig V4 Auth No Yes
  • 19. AWS IoT protocol comparison Capability MQTT HTTP Publish Yes Yes Subscribe Yes No Certificate Auth Yes Yes Sig V4 Auth No Yes
  • 20. AWS IoT protocol comparison Capability MQTT HTTP Publish Yes Yes Subscribe Yes Yes* Certificate Auth Yes Yes Sig V4 Auth Yes* Yes *Using WebSockets to upgrade HTTP connections to MQTT connections
  • 21. Authenticated • End-users sign in • Customize user-specific policy in AWS IoT • Users cannot access AWS IoT until IoT policy is attached Cognito Identities in AWS IoT Unauthenticated • No sign-in (anonymous) • Use IAM role policy and policy variables to restrict access • No user-specific policy in AWS IoT
  • 23. Unauthenticated access for end-users Amazon Cognito Get Credentials AssumeRole
  • 24. Connect through JavaScript var region = c.AWS.region; //'ap-northeast-1' var iotEndpoint = c.AWS.iotEndpoint; var identityPoolId = c.AWS.identityPoolId; AWS.config.region = region; AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: identityPoolId }); AWS.config.credentials.get(function(){ var signedUrl = getSignedUrl(); initClient(signedUrl); }); var requestUrl = 'wss://' + host + canonicalUri + '?' + canonicalQuerystring; //Unauthenticated
  • 25. Unauthenticated access for end-users Amazon Cognito Get Credentials AssumeRole AWS STS AWS IAM permissions role temporary security credentials
  • 26. Unauthenticated access for end-users Amazon Cognito AWS STS AWS IAM permissions role WebSocket Connect temporary security credentials Allowed? Yes!
  • 27. User-specific policies { "Effect": "Allow", "Action": ["iot:Publish", "iot:Subscribe"] "Resource": [ "arn:*:topic/home/123_aws_ave", "arn:*:topicfilter/home/123_aws_ave" ] } { "Effect": "Allow", "Action": ["iot:Publish", "iot:Subscribe"] "Resource": [ "arn:*:topic/home/456_iot_ln", "arn:*:topicfilter/home/456_iot_ln" ] } Policy for Alice, Bob: Policy for Chuck:
  • 28. Fine-grained access control SUB home/456_iot_ln SUB home/123_aws_ave/# PUB home/123_aws_ave/light_1/on SUB home/123_aws_ave/# PUB home/123_aws_ave/door_1/open Alice Bob Chuck
  • 29. Fine-grained access control PUB home/123_aws_ave/door_1/open SUB home/123_aws_ave/# PUB home/123_aws_ave/light_1/on SUB home/123_aws_ave/# PUB home/123_aws_ave/door_1/open Alice Bob Chuck
  • 30. Policy variables for Cognito users AWS IAM PUBLISH foo/us-east-1:abcdef-my-cognito-id temporary security credentials { "Effect": "Allow", "Action": "iot:Publish", "Resource": [ "arn:*:topic/foo/${cognito-identity.amazonaws.com:sub}" ] }
  • 31. Policy variables for Cognito users { "Effect": "Allow", "Action": "iot:Publish", "Resource": [ "arn:*:topic/foo/${cognito-identity.amazonaws.com:sub}" ] } AWS.config.region = 'us-east-1'; AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'us-east-1:YOUR_IDENTITY_POOL_ID' }); AWS.config.credentials.get(function(err)) { if (err) { return; } var cognitoId = AWS.config.credentials.identityId; mqttClient.connect(...); mqttClient.publish('foo/' + cognitoId); }); permissions role
  • 32. Outline • MQTT recap • WebSockets: what and why? • Authentication and Authorization • Demo + Code
  • 35. Configuring Cognito with AWS IoT UnauthenticatedAuthenticated
  • 36. Authenticated access for end-users Amazon Cognito Get Credentials temporary security credentials AWS STSAWS IAM permissions role temporary security credentials
  • 37. Connect through JavaScript var region = c.AWS.region; //'ap-northeast-1' var iotEndpoint = c.AWS.iotEndpoint; var identityPoolId = c.AWS.identityPoolId; AWS.config.region = region; AWS.config.credentials = new AWS.CognitoIdentityCredentials( { IdentityPoolId: c.AWS.identityPoolId, Logins: {'graph.facebook.com': fbresponse.authResponse.accessToken } }); AWS.config.credentials.get(function(){ var signedUrl = getSignedUrl(); initClient(signedUrl); }); var requestUrl = 'wss://' + host + canonicalUri + '?' + canonicalQuerystring; //Authenticated //After fb.login
  • 38. Connect through JavaScript function initClient(requestUrl) { var clientId = String(Math.random()).replace('.', ''); var client = new Paho.MQTT.Client(requestUrl, clientId); mqttClient = client; var connectOptions = { onSuccess: function() { client.subscribe(topiclightbulb); client.subscribe(topicgrove); }, useSSL: true, timeout: 3, mqttVersion: 4, onFailure: function() { console.error('connect failed'); } }; client.connect(connectOptions); client.onConnectionLost = onConnectionLost; client.onMessageArrived = onMessageArrived; } //Subscribe topics //Subscribe topics
  • 39. Authenticated access for end-users Amazon Cognito AWS STS AWS IAM permissions role WebSocket Connect temporary security credentials Allowed? Yes! IoT topic IoT shadow IoT policy
  • 40. Authenticated access for end-users Amazon Cognito AWS STS AWS IAM permissions role WebSocket Connect temporary security credentials Allowed? Yes! IoT topic IoT shadow IoT policy Create, Attach Policy for Alice, Bob, and Chuck
  • 41. Authenticated • End-users sign in • Customize user-specific policy in AWS IoT • Users cannot access AWS IoT until IoT policy is attached Cognito Identities in AWS IoT Unauthenticated • No sign-in (anonymous) • Use IAM role policy and policy variables to restrict access • No user-specific policy in AWS IoT
  • 42. Chicken and egg: when to attach the policy? • Users cannot connect until they have a policy in IoT • Policy cannot be attached without knowing the user’s CognitoId Solution: attach a policy when the user first connects!
  • 43. On-demand registration Amazon Cognito AWS Lambda CONNECT Access denied New User (already signed in) Get Credentials temporary security credentials (no policy for user)
  • 44. On-demand registration (continued) Amazon Cognito AWS Lambda Register()Create, Attach Policy New User IoT policy CONNECT OK! context.identity.cognitoIdentityId
  • 45. Lambda Code – Attach Principal Policy 'use strict'; var AWS = require('aws-sdk'); AWS.config.region = 'us-east-1'; var iot = new AWS.Iot(); exports.handler = (event, context, callback) => { var cognitoid = ‘'; if (typeof context.identity !== 'undefined') { cognitoid = context.identity.cognitoIdentityId; var params = { policyName: 'cognito-user-access', /* required */ principal: cognitoid /* required */ }; iot.attachPrincipalPolicy(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.log(data); // successful response }); } };
  • 46. What permissions to attach? • Start with minimal permissions • Dynamically generate or attach your policy base on user
  • 47. Wrapping up • WebSockets makes IoT interactive • Authentication for humans is different than devices • Use Lambda to drive user registration, pairing • Getting started with the AWS IoT Device SDK is easy • AWS IoT WebSockets, Rules Engine, Shadow and Lambda makes server-less applications easy