using amazon cognito and aws lambda to replace a...

71
Using Amazon Cognito and AWS Lambda to replace a traditional mobile app backend Bob Kinney Senior Software Development Engineer Amazon Cognito

Upload: vunhi

Post on 11-Jun-2018

240 views

Category:

Documents


1 download

TRANSCRIPT

Using Amazon Cognito and AWS Lambda to replace a traditional mobile app backend Bob Kinney Senior Software Development Engineer Amazon Cognito

Let's Build an App – Notes App

Authen'cate  users  

Authorize  access  

Analyze  User  Behavior  

Store  and  share  media  

Synchronize  data  

Deliver  media  

Store  shared  data  

Stream  real-­‐'me  data  Track  Reten'on  

Send  push  no'fica'ons  

Manage users and identity providers

Securely access cloud resources

Sync user prefs across devices

Track active users, engagement

Manage funnels, Campaign performances

Store user-generated photos Media and share them

Automatically detect mobile devices Deliver content quickly globally

Bring users back to your app by sending messages reliably

Store and query fast NoSQL data across users and devices

Collect real-time clickstream logs and take actions quickly

Your Mobile

App

AWS Mobile

Authen'cate  users  

Authorize  access  

Analyze  User  Behavior  

Store  and  share  media  

Synchronize  data  

AWS Mobile SDK

Amazon Mobile Analytics

Deliver  media  

Amazon Cognito (Sync)

AWS Identity and Access Management

Amazon Cognito (Identity)

Amazon S3 Transfer Manager

Amazon CloudFront (Device Detection)

Store  shared  data  Amazon DynamoDB (Object Mapper)

Stream  real-­‐'me  data  Amazon Kinesis (Recorder)

Track  Reten'on  Amazon Mobile Analytics

Send  push  no'fica'ons  Amazon SNS Mobile Push

Your Mobile

App

Authenticate users: Amazon Cognito

Amazon Cognito Overview

Manage authenticated and guest users across

identity providers

Guest  

Identity Management

Synchronize user’s data across devices and

platforms via the cloud

Data Synchronization

Securely access AWS services from mobile

devices and platforms  

Secure AWS Access

Guest   Your  own    Auth  

Identity Data Model

•  Identity Pool: Pool of app users. Can be shared across apps.

•  Identity: An individual user. Consistent across identity providers. Can be a guest user.

•  Login: Identifier in a login provider.

AWS  Account  

Dataset  

Iden0ty  Iden0ty  Iden0ty  

Dataset  Login  

Iden0ty    Pool  

1:60

1:n

0:n

Getting Started with Amazon Cognito in Three Steps

Sign up for an AWS Account and login to the AWS Management Console

Download and integrate the AWS Mobile SDK and store and sync user data in a dataset

Create identitypool for authenticated and unauthenticated users in the AWS Management Console

Amazon Cognito Authflow Login  

Amazon Cognito Authflow

Amazon Cognito Authflow

AssumeR

oleW

ithWeb

Iden

0ty  

Amazon Cognito Authflow

AssumeR

oleW

ithWeb

Iden

0ty  

Amazon Cognito Authflow

AssumeR

oleW

ithWeb

Iden

0ty  

All  this  is  handled  by  the  creden0als  provider.  

Unauthenticated Identities

Transitioning to Authenticated

Linking Logins

Merging Identities

Authorize access: Amazon Cognito + AWS IAM + Fine-grained access control

AWS IAM Roles •  Mechanism for delivering temporary credentials •  Has two policies

–  Trust (who can assume role) –  Access (what resources the role can access)

•  3 types roles –  AWS Service Roles –  Cross-Account Access –  Identity Provider Access

Roles for Amazon Cognito •  2 roles

–  Authenticated users –  Unauthenticated users

•  Access to Cognito Sync and Mobile Analytics •  Can be modified to support access to any AWS service •  Supports policy variables for fine-grained access control

Policy Variables – Amazon S3 <!-- Write/Read/Delete individual items -->

{

"Effect":"Allow",

"Action":["s3:PutObject","s3:GetObject","s3:DeleteObject"],

"Resource":"arn:aws:s3:::BUCKET_NAME/${cognito-identity.amazonaws.com:sub}/*"

}

<!-- List these items -->

{

"Effect":"Allow",

"Action":"s3:ListBucket",

"Resource":"arn:aws:s3:::BUCKET_NAME",

"Condition":{"StringLike":{"s3:prefix":"${cognito-identity.amazonaws.com:sub}/"}}

}

Policy Variables – Amazon S3 <!-- Write/Read/Delete individual items -->

{

"Effect":"Allow",

"Action":["s3:PutObject","s3:GetObject","s3:DeleteObject"],

"Resource":"arn:aws:s3:::BUCKET_NAME/${cognito-identity.amazonaws.com:sub}/*"

}

<!-- List these items -->

{

"Effect":"Allow",

"Action":"s3:ListBucket",

"Resource":"arn:aws:s3:::BUCKET_NAME",

"Condition":{"StringLike":{"s3:prefix":"${cognito-identity.amazonaws.com:sub}/"}}

}

Will  be  replaced  by  the  iden0ty  ID  

Policy Variables – Amazon DynamoDB

<!– DynamoDB policy -->

{

"Effect" : "Allow",

"Action" : [ "dynamodb:GetItem", "dynamodb:Query",

"dynamodb:PutItem", "dynamodb:UpdateItem" ],

"Resource" : "arn:aws:dynamodb:REGION:12345678:table/UserData",

"Condition" : {

"ForAllValues:StringEquals" : {

"dynamodb:LeadingKeys" : "${cognito-identity.amazonaws.com:sub}"

}

}

}

Policy Variables – Amazon DynamoDB

<!– DynamoDB policy -->

{

"Effect" : "Allow",

"Action" : [ "dynamodb:GetItem", "dynamodb:Query",

"dynamodb:PutItem", "dynamodb:UpdateItem" ],

"Resource" : "arn:aws:dynamodb:REGION:12345678:table/UserData",

"Condition" : {

"ForAllValues:StringEquals" : {

"dynamodb:LeadingKeys" : "${cognito-identity.amazonaws.com:sub}"

}

}

} Will  be  replaced  by  the  iden0ty  ID  

Sync App Data: Amazon Cognito

Amazon Cognito Sync Features

•  Store App Data, Preferences, and State Save app and user data to the cloud.

•  Work Offline Data persisted to local storage first. Local data is available regardless of connectivity.

•  No Backend Simple client SDK eliminates need for server side code.

User Data

Identity Pool

Sync data model

•  Identity Pool: Pool of app users. Can be shared across apps.

•  Identity: An individual user. Consistent across identity providers. Can be a guest user.

•  Dataset: Per user grouping of data. The most granular level of sync. Up to 1 MB.

•  Record: Key-value pair.

AWS  Account  

Dataset  

Iden0ty  Iden0ty  Iden0ty  

Dataset  Dataset  

Iden0ty    Pool  

1:60

1:n

1:20

Dataset  Dataset  Record  

1:1024

Amazon Cognito Synchronization

User Data

Amazon Cognito Synchronization

User Data

Amazon Cognito Synchronization

User Data

onConflict() {…

}

Amazon Cognito Synchronization

User Data

Amazon Cognito Synchronization

User Data

User Data

Amazon Cognito Sync Additional Features

•  Push Synchronization Integrate with Amazon SNS receive mobile push notifications when data changes.

•  Amazon Cognito Streams Integrate with Amazon Kinesis to get real time and/or bulk exports of your data. Backup to S3 or import into Amazon Redshift for analytics.

•  Amazon Cognito Events Integrate with AWS Lambda to Trigger a Lambda function on synchronization. Use for verification and/or modification of data before it's stored in Amazon Cognito.

Analyze User Behavior: Amazon Mobile Analytics

Amazon Mobile Analytics

Scalable and Generous Free Tier

Focus  on  metrics  that  ma@er.  Usage  reports  

available  within  60  minutes  of  receiving  data  from  an  

app.  

Fast

Scale  to  billions  of  events  per  day  from  millions  of  

users.  

Own Your Data

“Easily  collect,  visualize,  and  understand  your  app  usage  data  at  scale”

Data  collected  are  not  shared,  aggregated,  or  

reused.  

Key Business Metrics (with one line of code) 1.  Monthly  Ac0ve  Users  (MAU)    2.  Daily  Ac0ve  Users  (DAU)    3.  New  Users    4.  Daily  Sessions    5.  S0cky  Factor    6.  1-­‐Day  Reten0on    7.  Avg.  Revenue  per  DAU    8.  Daily  Paying  Users  9.  Avg.  Paying  DAU

Track  Reten'on    User  reten0on  is  a  key  indicator    to  judge  the  outcome  of  a  marke0ng  campaign,  new  feature  introduc0on,  UX  changes,  app  updates,  etc.      Mobile  Analy0cs  provide  four  charts  to  track  daily  or  weekly  rate  of  returning  users,  aYer  first  use  of  the  app.  

Get  behavioral  insights  into  app-­‐specific  ac0ons  that  your  users  take.  

Reports  provide  a  view  of  how  oYen  custom  events  occur.  You  can  add  further  context  with  A@ributes  and  Metrics,  to  each  custom  event.    Examples    

Track  the  number  of  Likes/Shares,  per  ar0cle,  in  a  news  app  

Understand  player  abort  rates  per  level,  in  a  game  

Number  of  songs  played,  per  user  session,  in  a  music  app  

In-­‐app  item  popularity  in  a  shopping  app  

Track Custom Events

Getting Started with Mobile Analytics in three steps

Sign up for an AWS Account and create or use an existing Cognito ID in the AWS Management Console

View engagement and session activity reports in the AWS Management Console within minutes

Download and integrate the AWS Mobile SDK with one line of code (Android/FireOS, iOS)

Store and share media: Amazon S3

Amazon S3 Connector: Transfer Manager

S3  Connector  

Mul0part  upload  media  (photos,  videos,  audio)  Fault  tolerant  download  (e.g.,  assets)  No  backend  required  Automa0c  retries  Pause,  resume,  cancel  func0ons  Op0mized  for  na0ve  OS  

Deliver Media: Amazon CloudFront

Amazon  S3   Custom  

OR  

User requests Edge location (cache + network optimizations) Origin

Get content Get content

Content Content

How  Amazon  CloudFront  Works  

Leverage AWS Edge Locations

Dallas  (2)  

St.Louis  

Miami  

Jacksonville  Los  Angeles  (2)  

Palo  Alto  

Sea@le  

Ashburn  (3)  

Newark  New  York  (3)  

Dublin  

London  (2)  

Amsterdam  (3)  Stockholm  

Frankfurt  (3)  Paris  (2)  

Singapore  (2)  

Hong  Kong  (2)  

Tokyo  (2)  

Sao  Paulo  

South  Bend  

San  Jose  

Milan  

Sydney  

Madrid  

Seoul  

Mumbai  

Chennai  

Atlanta  

Hayward  

Rio  de  Janeiro  

Marseille  

Warsaw  

Osaka  

Manila  

Taipei  

Melbourne  

Store Shared Data: Amazon DynamoDB

Joe Anna Bob

High  Scores  

Joe   1500  

Anna   800  

Bob   750  

Amazon DynamoDB Connector: Object Mapper

Simplifies  access  to  Amazon  DynamoDB  in  your  app    Map  client-­‐side  classes  to  Amazon  DynamoDB  tables    Removes  the  need  to  transform  objects  into  tables  and  vice  versa  

Send Push Notifications: Amazon SNS Mobile Push

SNS publishes notifications on your behalf using the credentials you obtain from each push service.

Apple  APNS  

Google  GCM  

Amazon  ADM  

Amazon  SNS  Mobile  Push  

SNS encapsulates each device token inside an Amazon Resource Name (ARN) endpoint.

Apple  APNS  

Google  GCM  

Amazon  ADM  

Amazon  SNS  Mobile  Push  

ARN  1  Token  A  

ARN  2  Token  B  

ARN  3  Token  C  

Once you register a device with SNS, SNS proactively consumes feedback about the corresponding token from the push service.

Amazon  SNS  Mobile  Push  

Token    Registra'on  

Token    Feedback  

Cloud  App  

You can access the underlying tokens and feedback, but you don’t have to do so in order to use SNS.

ARN endpoints remain stable, even if the underlying token is swapped or disabled.

Apple  APNS  

Google  GCM  

Amazon  ADM  

Amazon  SNS  Mobile  Push  

ARN  1  Token  A  

ARN  2  Token  B  

ARN  3  Token  C  

Token  X  

Token  Y  

You can publish unique messages to individual devices, or broadcast identical messages to many devices at once.

Publish  

Publish  

Publish  

Publish  

Direct  Publishing   Broadcast  with  SNS  Topics  

Grouping users by SNS Topic

Geography Activity Product

US  –  West  Coast   Daily  Ac0ves   Flapping  Bird  Rio  

Interest Tier Segment

49ers   Premium   Top  100  Players  

Run Your Own Backend: AWS Lambda

Event-Driven Compute in the Cloud •  Launched last November at re:Invent

–  Lambda functions: Stateless, request-driven code execution –  Triggered by events in other services:

•  PUT to an Amazon S3 bucket •  Write to an Amazon DynamoDB table •  Record in an Amazon Kinesis stream

–  Makes it easy to… •  Transform data as it reaches the cloud •  Perform data-driven auditing, analysis, and notification •  Kick off workflows

Data Triggers: Amazon S3

Amazon  S3  Bucket  Events   AWS  Lambda  

Original  image   Thumbnailed  image  

1  

2  

3  

Data Triggers: Amazon DynamoDB

AWS  Lambda  Amazon  DynamoDB  Table  and  Stream  

Send  SNS  no0fica0ons  

Update  another  table  

Mobile Compute: Building Backends with Lambda

Launching Mobile Compute •  Request/response •  AWS Mobile SDK •  Easy Personalization

…for devices …for end users

AWS  Lambda  Mobile  App  

Easy Personalization

Which device is she using?

?  

Which end user is this?

?  

Calling Lambda Functions •  Call from mobile or web apps

–  Wait for a response or send an event and continue –  AWS SDK, AWS Mobile SDK, REST API, CLI

•  Send events from Amazon S3 or SNS: –  One event per Lambda invocation, 3 attempts

•  Process DynamoDB changes or Amazon Kinesis records as events: –  Ordered model with multiple records per event –  Unlimited retries (until data expires)

Writing Lambda Functions

•  The Basics –  Stock node.js –  AWS SDK comes built in and ready to use –  Lambda handles inbound traffic

•  Stateless –  Use S3, DynamoDB, or other Internet storage for persistent data –  Don’t expect affinity to the infrastructure (you can’t “log in to the box”)

•  Familiar –  Use processes, threads, /tmp, sockets, … –  Bring your own libraries, even native ones

No Infrastructure to Manage

•  Focus on business logic, not infrastructure

•  Upload your code; AWS Lambda handles

•  Capacity •  Scaling •  Deployment •  Monitoring •  Logging •  Web service front end •  Security patching

Automatic Scaling

•  Lambda scales to match the event rate

•  Don’t worry about over or under provisioning

•  Pay only for what you use

•  New app or successful app, Lambda matches your scale

Bring your own code

•  Create threads and processes, run batch scripts or other executables, and read/write files in /tmp.

•  Include any library with your Lambda function code, even native libraries.

Other Event Sources for Lambda •  Amazon Simple Notification Service (SNS)

–  Easily target, route, transform, filter, or audit messages –  Trigger an AWS Lambda function by sending it notifications –  Turn Amazon CloudWatch alarms into actions

Lambda  Func0on  SNS  

Other Event Sources for Lambda •  Amazon Cognito

–  Before: Easily synchronize user data across their devices –  Now: Take action when that data changes –  Examples: Verify and respond to game state updates

Lambda  Func0on  Cognito  

Capture Real-time Data: Amazon Kinesis

Amazon Kinesis Connector: Kinesis Recorder

Kinesis  Connector  

Batching  of  requests  No0fica0on  when  batch  size  is  reached  Handles  any  arbitrary  data  

Authen'cate  users  

Authorize  access  

Analyze  User  Behavior  

Store  and  share  media  

Synchronize  data  

AWS Mobile SDK

Amazon Mobile Analytics

Deliver  media  

Amazon Cognito (Sync)

AWS Identity and Access Management

Amazon Cognito (Identity)

Amazon S3 Transfer Manager

Amazon CloudFront (Device Detection)

Store  shared  data  Amazon DynamoDB (Object Mapper)

Stream  real-­‐'me  data  Amazon Kinesis (Recorder)

Track  Reten'on  Amazon Mobile Analytics

Send  push  no'fica'ons  Amazon SNS Mobile Push

Your Mobile

App

Connect •  AWS Mobile Home

http://aws.amazon.com/mobile •  AWS Mobile Blog

http://mobile.awsblog.com

•  Twitter @awsformobile

•  Forums http://forums.aws.amazon.com

•  StackOverflow http://stackoverflow.com/tags/amazon-web-services

•  GitHub http://github.com/aws/ http://github.com/awslabs/