build mobile apps using aws sdks and aws mobile hub

51
© 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Olivier Klein 奧樂凱 Solutions Architect, Greater China April 2016 Build Mobile Apps using AWS SDKs and Mobile Hub

Upload: amazon-web-services

Post on 16-Apr-2017

849 views

Category:

Technology


0 download

TRANSCRIPT

© 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

Olivier Klein 奧樂凱Solutions Architect, Greater China

April 2016

Build Mobile Apps using

AWS SDKs and Mobile Hub

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Manage users and identity providers

and sync prefs across devices

Securely access

cloud resources

Test across multiple devices

and operating systems

Track active users,

engagement

Run stateless custom

code without servers

Store user-generated content

and share it

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 event logs

and take actions quickly

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

SDKs

Java Python (boto) PHP .NET Ruby Node.js

iOS Android Go

JavaScript

C++

OK let’s build an App!

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

• Authenticates your users

• Facebook, Google,

Amazon,Twitter, OpenID

• Anonymous

• Manages the users and

synchronize data across

multiple devices

• Allows secure communication

with other AWS services

Amazon Cognito

Amazon

Cognito

Initialize the Cognito Client

CognitoCachingCredentialsProvider cognitoProvider =

new CognitoCachingCredentialsProvider(

myActivity.getContext(), // get the context for the current activity

"AWS_ACCOUNT_ID",

"COGNITO_IDENTITY_POOL_ID",

"arn:aws:iam::AWS_ACCOUNT_ID:role/UNAUTHENTICATED_ROLE",

"arn:aws:iam::AWS_ACCOUNT_ID:role/AUTHENTICATED_ROLE",

Regions.US_EAST_1

);

// Create a service client with the provider

AmazonDynamoDB client = new AmazonDynamoDBClient(cognitoProvider);

Store and Synchronize Data

CognitoSyncManager syncClient = new

CognitoSyncManager(myActivity.getContext(),

COGNITO_POOL_ID, Regions.YOUR_REGION, cognitoProvider);

Dataset dataset = client.openOrCreateDataset("myDataset");

dataset.put("myKey", "my value");

String value = dataset.get("myKey");

dataset.remove("myKey");

dataset.synchronizeOnConnectivity(this, syncCallback);

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Control access to your AWS resources

• Create users, groups or roles

• Fine grained control access control with IAM

policies

• Control who can do what from where

• Permit resource access social identities

• Easily add multi factor authentication using

hardware tokens or smartphone apps

Identity and Access Management (IAM)

{

"Effect":"Allow",

"Action":["s3:*"],

"Resource":"*"

}

{

"Effect": "Allow",

"Action": ["cognito-sync:*"],

"Resource": "*"

}

{

"Effect": "Deny",

"Action": ["dynamodb:*"],

"Resource": "*"

}

Allow

Actions:

All S3

Sync store Operations

Resource:

All resources within

these services

Deny

Actions:

All DDB Operations

Resource:

All resources

Access Policy for IAM Role

Allow

Actions:

S3 Get/Put operations

Resource:

Only to a specific part

of bucket to that identity

{

"Effect": "Allow”,

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

"Resource": ["arn:aws:s3:::

myBucket/amazon/myapp/${cognito-identity.amazonaws.com:sub}"]

}

Allow

Actions:

DDB Get/Put operations

Resource:

Only to a specific cells in

the database

{

"Effect": "Allow”,

"Action": ["dynamodb:GetItem", "dynamodb:PutItem"],

"Resource" : [ "arn:aws:dynamodb:REGION:12345:table/TABLE_NAME”],

"Condition": {

"ForAllValues:StringEquals”:{

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

"dynamodb:Attributes”: ["Wins","Losses”,"TopScore",”DateTime" ]

},

}

Access Policy Restriction (Policy Variables)

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

AWS Device Farm

• Test your app on real devices in the

AWS cloud

• Fully managed and scalable test

platform

• Many different smartphone and tablet

models available

• Full built-in test suite

• Integration with custom frameworks

(e.g. Appium, Calabash etc.)

AWS Device

Farm

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Amazon Mobile Analytics

• Allows to collect, visualize and

understand your mobile app

usage

• Scales seamlessly to billions of

events per day

• You retain full control and

ownership of the data

Amazon Mobile

Analytics

Get insights into app

specific actions that

your users take

Examples

Track the number of

Likes/Shares in a

news app

Player abort rates

per level in a game

Number of songs

playedin a music app

In-app purchase item

popularity

Custom Events

Initialize Mobile Analytics

// Within your activity

private static MobileAnalyticsManager analytics;

// Within your activity onCreate()

try {

AnalyticsConfig options = new AnalyticsConfig();

options.withAllowsWANDelivery(true);

analytics = MobileAnalyticsManager.getOrCreateInstance(

getApplicationContext(),

"YOU MOBILE ANALYTICS APP ID",

Regions.US_EAST_1,

cognitoProvider

);

} catch(InitializationException ex) {

Log.e(this.getClass().getName(), "Failed to initialize Mobile Analytics", ex);

}

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

AWS Lambda

• Run your code in the cloud, fully

managed and highly-available

• Triggered through API calls or

state changes in your setup (S3,

DynamoDB, SNS, Kinesis)

• Scales automatically to match

the incoming event rate

• Charged per 100ms execution

time

Amazon

Kinesis

Amazon Lambda

Amazon

S3

Amazon

DynamoDBAmazon API

Gateway

Amazon

SNS

Adding a Lambda Backend to your App

Initialize the LambdaFactory and define the Interface for the functions

Call synchronize on the dataset

Create the Lambda Function

lambda = new LambdaInvokerFactory(context, Regions.US_WEST_2, provider);

//interface

@LambdaFunction(functionName="cloudFunction”)

String localFunction(String nameInfo);

lambda.localFunction(“Hello From “); // this will output “Hello From Lambda”

exports.handler = function(event, context) {

context.done(null, event + 'Lambda'); // SUCCESS with message

};

How to build an even better backend?

Back-end logic DatabaseMobile

Microservices with API Gateway and Lambda

Amazon

Lambda

Amazon API

Gateway

Amazon

DynamoDB

Microservice

Amazon API Gateway

• Fully managed and scalable RESTful

API gateway service

• Powered through our content

delivery network via our 53 global

edge locations

• Provides DDoS protection and

throttling capabilities

• Multiple API stages which you define

(e.g. dev, test, prod)

AWS Lambda

Amazon API

Gateway

Amazon

EC2

AWS API

On-prem

server

When to choose API Gateway vs. Direct SDK?

• Amazon API Gateway adds an additional layer

between your mobile users and your logic and

data stores in order to:

• Allow back-end logic to be interchanged without

mobile app code modifications

• Ability to throttle individual users or requests

• Protect against DDoS attacks including

counterfeit requests (Layer 7) and SYN floods

(Layer 3)

• Provides a caching layer for your calls

• Enables CORS for all AWS service for web apps

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Amazon S3 & Amazon CloudFront

• Amazon S3

• Highly available object storage

• Designed for 99.999999999% durability

• Offers HTTP / HTTPS endpoint to objects

• Amazon CloudFront

• Content Delivery Network with 54 edge

locations across the world

• Caches content on edge locations for low

latency

Amazon S3

Amazon

CloudFront

// Creating the transfer utility

AmazonS3 s3 = new AmazonS3Client(cognitoProvider);TransferUtility transferUtility =

new TransferUtility(s3, getApplicationContext());

// Upload file

TransferObserver observer = transferUtility.upload(bucket, filename, file);

// Download image

TransferObserver observer = transferUtility.download(bucket, filename, file);

Use Transfer Utility for S3

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Amazon SNS Mobile Push Notifications

• Amazon SNS is a fully

managed, cross-platform

mobile push intermediary

service

• Fully scalable to millions

of devices

• Allows to create topics

(e.g. per geo, interest,

usage pattern etc.)

Amazon SNS

Apple APNS

Google GCM

Amazon ADM

Windows WNS and

MPNS

Baidu CP

Android Phones and Tablets

Apple iPhones and iPads

Kindle Fire Devices

Android Phones and Tablets in China

iOS

Windows Phone Devices

Amazon

SNS

AmazonSNSClient snsClient = new AmazonSNSClient();

CreatePlatformEndpointRequest request = new CreatePlatformEndpointRequest()

.withPlatformApplicationArn(platformApplicationArn)

.withToken(deviceToken);

//register deviceCreatePlatformEndpointResult result =

snsClient.createPlatformEndpoint(request);

Device Registration – Code example

var sns = new SNS({ region: ’ap-southeast-1’});

// send message to single device (could also be a topic)

var endpointArn = 'arn:aws:sns:ap-southeast-1:12345678:endpoint/5d3954e1-7d68-365a-80c2-95ae98ae4336';

// Message to send

var message = ’New player just joined your game!';

sns.sendMessage(endpointArn, message, function(err, messageId) {

if (err)

console.log(’Error occured with device %s', endpointArn);

});

Send Push Notifications via AWS Lambda

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Amazon DynamoDB

• Schemaless Data Model

• Seamless scalability

• No storage or throughput limits

• Consistent low latency performance

• High durability and availability

• Replicated across 3 facilities

DynamoDB

table

items

attributes

Fully Managed NoSQL Database Service

@DynamoDBTable(tableName = ”User")

public static class User {

private String hash, nickname, avatar;

private int score;

@DynamoDBHashKey(attributeName = ”hash")

public String getHash() {

return hash;

}

public void setHash(String hash) {

this.hash = hash;

}

@DynamoDBAttribute(attributeName=”nickname")

public String getNickanme() {

return nickname;

}

...

hash nickname avatar score

abce6 Oli4 s3://bkt/av1.jpg 1500

feru64 LoLZ s3://bkt/lolz56.jpg 800

4568c L33t s3://bkt2/cat.png 750

Table: User

Object Mapper Example - Class

// Create a user object

User user = new User();

note.setHash(”abce64”);

note.setNickname(”Oli4");

note.setAvatar(”s3://mybucket/av1.jpg");

note.setScore(0);

// Save user object to DynamoDB

mapper.save(user);

// Update score and save user again

user.setScore(user.getScore()+100);

mapper.save(user);

// Load another user

User anotherUser = mapper.load(User.class,”asian_tiger_1234”);

Object Mapper Example – Store and Update

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Stream in Real Time: Amazon Kinesis

• Real-Time Data Processing over

large distributed streams

• Elastic capacity that scales to

millions of events per second

• React In real-time upon incoming

stream events

• Reliable stream storage

replicated across 3 facilitiesAmazon Kinesis

KinesisRecorder

String kinesisDirectory = "YOUR_UNIQUE_DIRECTORY";

KinesisRecorder recorder = new KinesisRecorder(

cognitoProvider,

Regions.AP_SOUTHEAST_1,

getDir(kinesisDirectory, MODE_PRIVATE));

recorder.saveRecord(”Message1".getBytes(),"MyStreamName");

recorder.saveRecord(”Message2".getBytes(),"MyStreamName");

recorder.submitAllRecords();

Process and Notify in AWS Lambda

exports.handler = function(event, context) {

event.Records.forEach(function(record) {

payload = new Buffer(record.kinesis.data, 'base64').toString('ascii');

UserEvent event = new UserEvent(payload);

if (event.position == TREASURE_BONUS_COORD) {

var message = ’You found the special treasure!';

sns.sendMessage(endpointArn, message);

}

});

context.succeed();

};

Amazon Mobile

Analytics

Amazon Device Farm

AWS IAM

Amazon Cognito Amazon S3

Amazon CloudFront

Amazon DynamoDB

Amazon Lambda

Amazon SNS

Mobile Push

AWS Mobile SDK

Amazon Kinesis

Authenticate & Sync

Authorize access

Analyze User Behavior

Store Content

Test across

Devices

Deliver Content

Store Data

Record Real-Time EventsRun Business Logic

Send Push Notifications

Great, AWS has all we need, but it’s a bit complex!

AWS Mobile Hub

• Allows to build mobile apps within

minutes

• Single integrated console to use all

AWS services for mobile

• Automatically provisions all necessary

AWS services based on selected features

• Automatic code generation for iOS

(Objective-C / Swift) and Android

• Uses security best practices with

AWS IAM

AWS Mobile Hub

Create a project and add features

Thank you!

Olivier Klein 奧樂凱Solutions Architect, Greater China