Top Banner
© 2015, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Building Secure and Scalable APIs Paul Maddox, Solutions Architect @paulmaddox Using Amazon API Gateway and AWS Lambda
45

Building Secure Mobile APIs

Apr 15, 2017

Download

Business

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Building Secure Mobile APIs

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

Building Secure and Scalable APIs

Paul Maddox, Solutions Architect@paulmaddox

Using Amazon API Gateway and AWS Lambda

Page 2: Building Secure Mobile APIs

Imagine for a minute…

Being able to develop a mobile backend API that:

• Requires no infrastructure

• Scales automatically to meet demand

• Has granular costs that grow with usage

Page 3: Building Secure Mobile APIs

The services we are going to use

Amazon API GatewayAWS Lambda Amazon Cognito Amazon DynamoDB

Host the API and route API calls

Execute our app’s business logic

Generate temporary AWS credentials

Data store

Page 4: Building Secure Mobile APIs

Our destination

1. A new, fully-managed development model2. Declare an API with Amazon API Gateway3. Application logic in AWS Lambda4. Enable user signup and authentication with Amazon

Cognito User Pools5. Generate and connect the Client SDK

Page 5: Building Secure Mobile APIs

First building block:AWS Lambda

Page 6: Building Secure Mobile APIs

High performance at any scale; Cost-effective and efficient

No Infrastructure to manage

Pay only for what you use: Lambda automatically matches capacity to

your request rate. Purchase compute in 100ms increments.

Bring Your Own Code

Lambda functions: Stateless, trigger-based code execution

Run code in a choice of standard languages. Use threads, processes,

files, and shell scripts normally.

Focus on business logic, not infrastructure. You upload code; AWS

Lambda handles everything else.

AWS Lambda Overview

Page 7: Building Secure Mobile APIs

AWS Lambda ConsoleDevelop, test and publish your Lambda functions either by the AWS Management Console, AWS CLI or our SDKs.

Or use community frameworks such as serverless.com, gosparta.io and more…

Page 8: Building Secure Mobile APIs

Second building block: Amazon API Gateway

Page 9: Building Secure Mobile APIs

Amazon API Gateway overview

Manage deployments to multiple versions and

environments

Define and host APIs

Leverage Identity and Access Management to authorize access to your

cloud resources

Leverage AWS Auth

DDoS protection and request throttling to

safeguard your back end

Manage network traffic

Page 10: Building Secure Mobile APIs

Your Feedback

Managing multiple versions and stages of an API is difficult

Monitoring 3rd party developers’ access is time consuming

Access authorization is a challenge

Traffic spikes create operational burden

What if I don’t want servers at all?

Page 11: Building Secure Mobile APIs

Host multiple versions and stages of your APIs

Create and distribute API Keys to developers

Authenticate and authorise API consumers

Throttle and monitor requests to protect your backend

Utilizes AWS Lambda

Introducing Amazon API Gateway

Page 12: Building Secure Mobile APIs

Introducing Amazon API Gateway

Managed cache to store API responses

Reduced latency and DDoS protection through CloudFront

SDK Generation for iOS, Android and JavaScript

Swagger import and export support

Request / Response data transformation and API mocking

Page 13: Building Secure Mobile APIs

Managed

Putting it all together…

InternetMobile appsAWS Lambda

functions

AWS

API Gateway cache

Endpoints on Amazon EC2

Any other publicly accessible endpoint

Amazon CloudWatch

Amazon CloudFront

API Gateway

API GatewayOther AWS services

AWS Lambda functions

Page 14: Building Secure Mobile APIs

Securing our APIAuthentication, authorisation and accounting (AAA)

Page 15: Building Secure Mobile APIs

Third building block: Amazon Cognito User Pools

Page 16: Building Secure Mobile APIs

A Fully Managed User Directory in Cognito

Add sign-up and sign-in easily to your mobile and

web apps

Easy User Management

Verify phone numbers and email addresses and offer multi-factor authentication

Enhanced Security Features

Launch a simple, secure, low-cost, and fully managed

service to create and maintain a user directory

that scales to 100s of millions of users

Managed User Directory

Page 17: Building Secure Mobile APIs

Comprehensive User Scenarios

Email or phone number Verification

Forgot Password

User sign-up and sign-in

Users verify their email address or phone number prior to activating an account

Users can change their password if they forget it

Users sign-up using email, phone number or user name and password.Users can then sign-in.

User Profile Retrieve and update user profiles, including custom attributes

SMS-based MFA If enabled, users complete Multi-Factor Authentication (MFA) with a confirmation code via SMS as part of sign-in and forgot password flows

Page 18: Building Secure Mobile APIs

Comprehensive Administrator Scenarios

Manage users in a User Pool

Select Email and Phone Verification

Customize with Lambda Triggers

Setup Password Policies

Create and manageUser Pools

List, search and perform actions on specific user(s) in the User Pool

Configure verifications of users’ email addresses and phone numbers (via SMS)

Create functions in AWS Lambda to customize workflows

Control password requirements like minimum length, uppercase, and inclusion of special characters

Create, configure and delete multiple User Pools in their AWS account

Define Attributes Select required attributes and Define custom user attributes

Page 19: Building Secure Mobile APIs

Secure Sign-in Made Easy

Token-based Authentication

Secure Remote Password Protocol

SMS-based Multi-factor Authentication

Uses tokens based on OpenID Connect (OIDC) and OAuth 2.0 standards

Uses Secure Remote Password (SRP) for secure password handling end to end

Enables your end users to user the text messaging functionality of a mobile phone as an extra layer of security

Page 20: Building Secure Mobile APIs

Customization using Lambda hooks

Lambda Hook Example Scenarios

Pre user sign-up Custom validation to accept or deny the sign-up request

Custom message Advanced customization and localization of verification messages

Pre user sign-in Custom validation to accept or deny the sign-in request

Post user sign-in Event logging for custom analytics

Post user confirmation Custom welcome messages or event logging for custom analytics

Page 21: Building Secure Mobile APIs

Authentication FlowAmazon Cognito

User Pools

Amazon API Gateway

Custom AuthorizerLambda Function

/pets Lambda Function

/n… Lambda Function

Amazon DynamoDB Th

rottl

ing

Cac

he

Logg

ing

Mon

itorin

g

Auth

Mobile apps

Lets walk through this step by step…

Page 22: Building Secure Mobile APIs

Authentication FlowAmazon Cognito

User Pools

Amazon API Gateway

Custom AuthorizerLambda Function

/pets Lambda Function

/n… Lambda Function

Amazon DynamoDB Th

rottl

ing

Cac

he

Logg

ing

Mon

itorin

g

Auth

Mobile apps

Step 1: User signs up for an account with our Amazon Cognito User Pool, providing their email, telephone number & password (+ any custom attributes).

Amazon Cognito can automatically verify the user’s email address and/or phone number if required.

Page 23: Building Secure Mobile APIs

Authentication FlowAmazon Cognito

User Pools

Amazon API Gateway

Custom AuthorizerLambda Function

/pets Lambda Function

/n… Lambda Function

Amazon DynamoDB Th

rottl

ing

Cac

he

Logg

ing

Mon

itorin

g

Auth

Mobile apps

Step 2: At some point in the future, the user wants to sign in. We can now authenticate the user.

Page 24: Building Secure Mobile APIs

Authentication FlowAmazon Cognito

User Pools

Amazon API Gateway

Custom AuthorizerLambda Function

/pets Lambda Function

/n… Lambda Function

Amazon DynamoDB Th

rottl

ing

Cac

he

Logg

ing

Mon

itorin

g

Auth

Mobile apps

Optional: If MFA is enabled (either for this user, or all users), Amazon Cognito will SMS or email a one time authentication code to the user.

Page 25: Building Secure Mobile APIs

Authentication FlowAmazon Cognito

User Pools

Amazon API Gateway

Custom AuthorizerLambda Function

/pets Lambda Function

/n… Lambda Function

Amazon DynamoDB Th

rottl

ing

Cac

he

Logg

ing

Mon

itorin

g

Auth

Mobile apps

Step 3: After a successful authentication, Amazon Cognitoresponds with a signed JSON Web Token (JWT) containing the user’s details.

Page 26: Building Secure Mobile APIs

Wait… What is a JSON Web Token (JWT)?

* https://jwt.io

Cryptographically verifiable claims

Page 27: Building Secure Mobile APIs

Authentication FlowAmazon Cognito

User Pools

Amazon API Gateway

Custom AuthorizerLambda Function

/pets Lambda Function

/n… Lambda Function

Amazon DynamoDB Th

rottl

ing

Cac

he

Logg

ing

Mon

itorin

g

Auth

Mobile apps

Step 4: You are now ready to call your backend API’s from your mobile application.

The JWT is passed in via the Authorization HTTP header.

GET /pets HTTP/1.1Host: ...Authorization: eyJraWQiOi…

Page 28: Building Secure Mobile APIs

Authentication FlowAmazon Cognito

User Pools

Amazon API Gateway

Custom AuthorizerLambda Function

/pets Lambda Function

/n… Lambda Function

Amazon DynamoDB Th

rottl

ing

Cac

he

Logg

ing

Mon

itorin

g

Auth

Mobile apps

Step 5: API Gateway calls your custom authorizer function which validates the JWT token and creates an IAM policy that defines which API resources the user can access (based on their user attributes in the JWT claims).

GET /pets HTTP/1.1Host: ...Authorization: eyJraWQiOi…

Page 29: Building Secure Mobile APIs

Authentication FlowAmazon Cognito

User Pools

Amazon API Gateway

Custom AuthorizerLambda Function

/pets Lambda Function

/n… Lambda Function

Amazon DynamoDB Th

rottl

ing

Cac

he

Logg

ing

Mon

itorin

g

Auth

Mobile apps

Step 6: Additionally, the custom authorizer function will need to check that the JWT hasn’t been tampered with.

To do this, it needs the signing public key (JWK) from Amazon Cognito.

GET /pets HTTP/1.1Host: ...Authorization: eyJraWQiOi…

Page 30: Building Secure Mobile APIs

Authentication FlowAmazon Cognito

User Pools

Amazon API Gateway

Custom AuthorizerLambda Function

/pets Lambda Function

/n… Lambda Function

Amazon DynamoDB Th

rottl

ing

Cac

he

Logg

ing

Mon

itorin

g

Auth

Mobile apps

Step 7: If authentication was successful, the API call will be passed through to the backend Lambda functions where your logic sits.

Authentication is cached for each token (up to 1 hour).

GET /pets HTTP/1.1Host: ...Authorization: eyJraWQiOi…

Page 31: Building Secure Mobile APIs

Versioning our API

Page 32: Building Secure Mobile APIs

API Configuration

You can create APIs

Define resources within an API

Define methods for a resource• Methods are Resource + HTTP verb

Pet Store

/pets

/pets/{petId}• GET• POST• PUT

Page 33: Building Secure Mobile APIs

API Stages (environments)

API Configuration can be deployed to a stage. Stages are different environments

For example:

• Dev

• Beta

• Prod

• As many stages as you need

Pet Store

prod

gamma

beta

dev

Page 34: Building Secure Mobile APIs

Breaking Changes

At some point in time, you may need to break your API contract.

Just clone your v1 API and point your custom domain name/path to the correct stage.

https://api.example.com/v1/

https://api.example.com/v2/

Tip: Plan for this ahead of time, and start with /v1/

Pet Store

prod

gamma

beta

dev

Pet Store

prod

gamma

beta

dev

Version 1 Version 2

Page 35: Building Secure Mobile APIs

Breaking Changes: Clone the v1 API to v2

Page 36: Building Secure Mobile APIs

Breaking Changes: Map our domain + paths

api.example.com api.example.com to

api.example.com

example

Page 37: Building Secure Mobile APIs

Managing our API with Swagger

Page 38: Building Secure Mobile APIs

What is Swagger?

* https://swaggerhub.com

• Open source language for defining APIs.

• Automatically generate API documentation.

• Publish your API definition to your developers and consumers!

Page 39: Building Secure Mobile APIs

Benefits of using Swagger

• API definitions live in our source repository with the rest of the app.

• They can be used with other utilities in the Swagger toolset (for example, documentation generation or debugging with Postman*).

• API can be imported and deployed in our build scripts.

* https://getpostman.com

Page 40: Building Secure Mobile APIs

Consuming our API

Page 41: Building Secure Mobile APIs

1-click SDK generationGenerate SDK’s for your API consumers.

Available for:

• Android• iOS• Javascript

Also available from our CLI tools or API

$ aws apigateway get-sdk

Page 42: Building Secure Mobile APIs

Generated SDK benefits

The generated client SDK knows how to:

• Authenticate with your API (SigV4 or custom auth like JWT)

• Handle-throttled responses with exponential back-off

• Marshal and unmarshal requests and responses to model objects

Pet roofus = new Pet();

roofus.setType(Animals.Dog)

roofus.setLanguage(Lang.WoofWoof);

Page 43: Building Secure Mobile APIs

What have we learned?

AWS Lambda + Amazon API Gateway mean no infrastructure to manage – we scale for you

Lots of examples published on the AWSLabs GitHub accounthttps://github.com/awslabs/

Security is important, and complex – use Cognito User Pools as a secure identity provider (IdP) for your applications

API Versioning doesn’t need to be hard. With Swagger import and client SDK – we can automate most workflows

Page 44: Building Secure Mobile APIs

Pricing Example

Amazon API Gateway (our example = $40.50/month):

Free tier: 1,000,000 requests/month$3.50/million thereafterplus $0.09/GB outbound data transfer

AWS Lambda (our example = $1.80/month):

Free tier: 1,000,000 invocations/month$0.20/million thereafterplus $0.00001667 per GB/second of memory

Amazon Cognito User Pools (our example = $0.00/month):

Free tier: 50,000 monthly active users (MAU)$0.00550/MAU thereafterTiered pricing available for large quantities

Our API services 10,000,000 requests/month, each request invokes a Lambda function that takes 100ms and uses 128MB of memory.We also have a Cognito User Pool with 50,000 monthly active users.

Or… $0.01 per user per year

$42.30 per month

Page 45: Building Secure Mobile APIs

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

Thank you!

Paul Maddox, Solutions Architect@paulmaddox