45
© 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

Building Secure Mobile APIs

Embed Size (px)

Citation preview

© 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

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

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

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

First building block:AWS Lambda

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

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…

Second building block: Amazon API Gateway

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

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?

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

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

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

Securing our APIAuthentication, authorisation and accounting (AAA)

Third building block: Amazon Cognito User Pools

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

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

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

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

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

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…

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.

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.

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.

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.

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

* https://jwt.io

Cryptographically verifiable claims

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…

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…

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…

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…

Versioning our API

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

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

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

Breaking Changes: Clone the v1 API to v2

Breaking Changes: Map our domain + paths

api.example.com api.example.com to

api.example.com

example

Managing our API with Swagger

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!

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

Consuming our API

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

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);

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

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

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

Thank you!

Paul Maddox, Solutions Architect@paulmaddox