2. ¿Qué vamos a ver en esta sesión?
1. Nuevo modelo de desarrollo: Completamente
gerenciado
2. Declarar APIs con Amazon API Gateway
3. Lógica de la aplicación en AWS Lambda
4. APIs de Login y Registro, utilizando Amazon Cognito
5. Autorización utilizando AWS IAM (STS)
6. Generación de SDK para cliente
3. Totalmente Gerenciado
API: Modelo Totalmente gerenciado
InternetMobile apps
Funciones
AWS Lambda
AWS
API Gateway
cache
Endpoints en
Amazon EC2
Cualquier otro
endpoint público
Amazon
CloudWatch
Amazon
CloudFront
API
Gateway
API Gateway
Otros
Servicios
AWS
Funciones
AWS Lambda
4. Puntos Principales
AWS Lambda + Amazon API Gateway =
0 (cero) infraestructura para administrar
Seguridad = Prioridad:
Aproveche la integración con AWS Identity and
Access Management
Swagger + client SDK = Automatización de workflows
5. Servicios que vamos a utilizar
Amazon API Gateway AWS Lambda Amazon Cognito Amazon DynamoDB
Publica las APIs y
enruta las llamadas
Ejecuta: Lógica de
autenticación y lógica
de la aplicación
Gerencia de
identidades y entrega
credenciales AWS
Almacén de datos:
Usuarios y Mascotas
7. No-Autenticadas
Flujo de las llamadas
Mobile apps
AWS Lambda lambdaHandler
Register (/user-POST)
Login (/login-POST)
API Gateway
Autenticadas
Mobile apps AWS Lambda lambdaHandler
ListPets (/pets – GET)
GetPet (/pets/{petId}-GET
API Gateway
Assume Role
CreatePet (/pets – POST)
Sigv4
Usando las
credenciales AWS
Invoca con las
credenciales AWS Autorizado por IAM
Recibe
credenciales AWS
APIs:
/user
/login
APIs:
/pets
/pets/{petId}
Table: petstoreapp-users
IdentityPool: PetStoreApp
Table:
petstoreapp-pets
8. ¿Qué tiene de diferente este modelo?
“Serverless” – La aplicación puede usar muchos
servidores, pero no necesito administrar ninguno.
Autorización: Realizada por AWS, basada en Roles
Definición e implementación de APIs usando
Swagger
10. Amazon API Gateway - Conceptos
Gerenciamiento de
implementaciones –
múltiples versiones y
ambientes (stages)
Definición y
Publicación de APIs
Usa las credenciales de
AWS IAM para el control
de acceso a sus recursos
(Como si fueran servicios
AWS)
Aprovecha los mecanismos
de Autorización de AWS
Gestión de tráfico de
red
Protección DDoS y
“Throttling”
11. Modelo de API: Recursos, Métodos e Integración
rest-api-id
resou
rce-id
ARN
12. Recursos y Métodos
• POST – Recibe usuario y
contraseña; registra (crea) el
nuevo usuario en DynamoDB
/users
• POST – Recibe usuario y
contraseña; autentica; solicita
credenciales AWS a cognito y las
retorna a la App
/login
• POST – Recibe los datos de la
mascota;los guarda en DynamoDB
• GET – Retorna una lista de
mascotas desde DynamoDB
/pets
• GET – Retorna la información de la
mascota, a partir de su petID/pets/{petId}
No Autenticado
Autenticado
14. Method Response
Integration
(Req. & Resp)
Method Request
Method
Usando Swagger para automatizar el proceso
/users:
post:
summary: Registers a new user
consumes:
- application/json
produces:
- application/json
parameters:
- name: NewUser
in: body
schema:
$ref: '#/definitions/User’
x-amazon-apigateway-integration:
type: aws
uri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31...
credentials: arn:aws:iam::964405213927:role/pet_store_lambda_invoke
...
responses:
200:
schema:
$ref: '#/definitions/RegisterUserResponse'
15. Usando Swagger para automatizar el proceso
Usando AWS CLIaws apigateway import-rest-api --body file://swagger.yaml
Usando la Consola
16. Beneficios de usar Swagger
• Las definiciones de las API permanecen en su
repositorio, con el resto del código de la aplicación.
• Pueden ser usadas en conjunto con otras utilidades de
Swagger (por ejemplo, generación de documentación).
• Las APIs pueden ser importadas e implementadas en
su propio script.
18. Escalabilidad y Alto desempeño;
Eficiente y Económica
No hay infraestructura para
administrar
Pague solo por lo que use: Lambda
adecúa automáticamente la
capacidad para responder a los
volúmenes de solicitudes.
Use su propio código
Funciones Lambda : Ejecución de código basada en eventos, Stateless
Ejecute su código en una variedad
de lenguajes estándar. Use threads,
procesos, archivos y shell scripts, de
la forma usual.
Enfóquese en su lógica de negocio.
Cargue su código y AWS Lambda se
encarga del resto.
AWS Lambda - Conceptos
19. Lambda handler.
lambdaHandler
(en el código
Java)
Acción: Register
Acción: Login
Acción:
Create Pet
Acción:
Get Pet
Gestión de
identidades
Pet store
database
Amazon API
Gateway
Integration request
User
database
20. Excepciones mapeadas a HTTP Status.
Register action
Login action
Create Pet action
Get Pet action
BadRequestException
BAD_REQUEST +
Stack Trace
InternalErrorException
INTERNAL_ERROR +
Stack Trace
lambdaHandler
(en el código
Java)
Amazon API
Gateway
responses:
"default":
statusCode: "200"
"BAD.*":
statusCode: "400"
"INT.*":
statusCode: "500"
21. Mapping Template es una herramienta poderosa
Encuentre más acerca de nuestros ”mapping templates”:
http://amzn.to/1L1hSF5
23. Amazon Cognito - Conceptos
Gestión de usuarios
autenticados e invitados,
entre diferentes
proveedores de identidad
Gestión de Identidad
Sincroniza datos de los
usuarios entre dispositivos
y plataformas, via nube
Sincronización de
datos
Facilita el acceso seguro
a servicios AWS desde
plataformas y
dispositivos móviles
Acceso seguro a
recursos AWS
24. Definición de las APIs (No Autenticadas)
• POST
• Recibe un usuario y contraseña
• Encripta la contraseña (con salt) y registra la
cuenta del usuario en DynamoDB
• Hace una llamada a Cognito, para registrar
el usuario y generar las credenciales
• Retorna las informaciones de usuario y
credenciales temporales
/users
• POST
• Recibe un usuario y contraseña
• Autentica el usuario (contra la información
en DynamoDB)
• Si la autenticación es exitosa, hace una
llamada a Cognito para generar credenciales
• Retorna las credenciales temporales
/login
25. Recibiendo las credenciales temporales.
Llamada a la API
login
(sin autenticación)
Cliente API
Gateway
Backend
/login
Login
action
BD
Usuarios
Credenciales OK
Solicita OIDC
Obtiene el token
OpenID
Recibe las
credenciales
AWS para firmar
las llamadas API
Usando el token
OIDC, solicita
credenciales AWS
Genera las
credenciales AWS
Access key +
secret key +
session token
/login
1.
2.
3.
28. APIs /pets (necesitan AuthN y AuthZ)
• POST
• Recibe información de la mascota
(nombre, tipo)
• Graba en DynamoDB
• Retorna el petID creado
• GET
• Retorna la lista de mascotas almacenada
en DynamoDB (incluyendo el petID)
/pets
• GET
• Recibe (en el path) el petID
• Usando mapping templates, se pasa el
parámetro petID a la función Lambda
• Busca la información de la mascota en
DynamoDB
• Retorna la información de la mascota
/pets/{petId}
30. API Gateway repasa las autorizaciones
credentials:
arn:aws:iam::*:user/*
En la consola En el archivo Swagger
31. El Rol IAM define la autorización
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:Scan",
"lambda:InvokeFunction",
"execute-api:invoke"
],
"Resource": [
"arn:aws:dynamodb:us-east-1:xxxxxx:table/test_pets",
"arn:aws:lambda:us-east-1:xxxxx:function:PetStore”,
"arn:aws:execute-api:us-east-1:xxxx:API_ID/*/POST/pets"
]
}
]
}
En este ejemplo, el rol permite
accesos a:
• DynamoDB
• API Gateway
• Lambda
Y permite definir acceso
solamente a recursos
específicos en esos servicios
32. Y todavía hay más: Fine-grained access permissions
Internet
Cliente
API
Gateway
Funciones
AWS Lambda
Amazon
CloudFront
DynamoDB
CognitoId2
…
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": [”${cognito-
identity.amazonaws.com:sub}"],
"dynamodb:Attributes": [
"UserId","GameTitle","Wins","Losses",
"TopScore","TopScoreDateTime”
]
},
"StringEqualsIfExists": {
"dynamodb:Select": "SPECIFIC_ATTRIBUTES”
}
}
…
Ejecuta con el
rol definido
UserID Wins Losses
cognitoId1 3 2
cognitoId2 5 8
cognitoId3 2 3
Informaciones de contexto (Cognito ID) son repasadas …
Con eso, AWS Lambda & DynamoDB seguirán coherentemente la política de acceso
33. Flujo autenticado completo
Mobile apps AWS Lambda lambdaHandler
API Gateway
Sigv4
Usa los mismos
permisos de las
credenciales de
usuario
Llamadas a los
servicios son
autorizadas
usando un rol
IAM
Documentación acerca de FGAC:
http://amzn.to/1YkxcjR
DynamoDB
34. Beneficios de usar AWS IAM (AuthN & AuthZ)
• Separación de funciones – la estrategia de
autorización se delega a un servicio dedicado
• Gestión centralizada de acceso, a través de un
conjunto único de políticas
• Credenciales y Roles pueden ser modificadas o
deshabilitadas con una llamada API
39. Beneficios del SDK generado
El SDK de cliente contiene la lógica para:
• Firmar las llamadas API usando sigv4
• Manejar respuestas reguladas (throttled)
• Marshal/unmarshal solicitudes y respuestas en objetos
40. AWS Lambda + Amazon API Gateway =
0 (cero) infraestructura para administrar
Seguridad = Prioridad:
Aproveche la integración con AWS Identity and
Access Management
Swagger + client SDK = Automatización de workflows
¿Qué vimos hoy?
Este ejemplo está disponible en la cuenta GitHub AWSLabs
https://github.com/awslabs/api-gateway-secure-pet-store
41. ¡Gracias !
Este ejemplo está disponible en la cuenta GitHub AWSLabs
https://github.com/awslabs/api-gateway-secure-pet-store
Hinweis der Redaktion
¿
¡
A new, fully-managed development model : Model where AWS takes care of the infrastructure.
And, how the Amazon API Gateway integrates with other services:
Declare an API with Amazon API Gateway
Application logic in AWS Lambda
Register and login API with Amazon Cognito
Authorization with AWS IAM
Generate and connect the Client SDK
The first thing we want to look at is the standard flow of an API call, including all components in the system
First, a request comes in from a client, this could be a mobile device, a web application or a backend service
The requests arrives at one of our CloudFront PoP locations, it’s accepted and routed through to the API Gateway in the customer’s region
The API Gateway receives the request, then checks for records in the dedicated cache (if it is configured). If there are no cached records available then it will forward the request to the backend for processing
The backend can be a Lambda function, a web service running on Amazon EC2, or any other publicly accessible web service
Once the backend has processed the request the API call metrics are logged in Amazon CloudWatch and the content is returned to the client
First understand what has driven the decision to build API Gateway, from customer feedback to wider strategic decisions and market forces
Next, look at how the service works, and helps customers with their API services
Finally, open it out for Q&A at the end
Key Takeaways
AWS Lambda + Amazon API Gateway means no infrastructure to manage – we scale for you
Security is important, and complex – make the most of AWS Identity and Access Management. Security is a priority, take advantage of Authentication (Cognito) and Authorization (IAM) integration with API Gateway.
Swagger import and client SDK – we can automate most workflows
API Gateway: Host the API and route API calls
AWS Lambda: Execute our app’s business logic
Amazon Cognito: Generate temporary AWS credentials
Amazon DynamoDB: Data store
It is not serverless, it is just that the application can use lots of servers, and I don’t need to manage a single one.
Authorization of API calls is delegated to AWS. We just need to focus on our IAM roles.
Deployment of the API is automated using Swagger.
API definition and Swagger
API Gateway offers an “abstraction” of API or Backend logic.
Interface for developers (like a FrontEnd). You can keep the FrontEnd while doing modifications/improvements to the backend logic.
Define and host APIs: Manage deployments to multiple versions and environments
Manage network traffic: We have learnt a lot about manage network traffic throughout the years. DDoS protection and request throttling to safeguard your back end. (Layer 7/App (Scaling) and Layer 3 (syn flood))
Leverage AWS Auth: Leverage Identity and Access Management to authorize access to your cloud resources. Convert your API as if it were an AWS Service!!!! (every API method receives an ARN)
Left side: Public-side vs Right side: Integration with backend.
Demo 0:
Show the User App
Start with the reset app, to create a new user
Then: login and Get pets)
Show the Cloudwatch logs, showing the /login and the /pets calls
Show the tables in DynamoDB
Left side: Public-side vs Right side: Integration with backend.
API Gateway handles resources as typed objects. Resources can have models associated with them.
Models are simply the JSON schema representation of the request and response data models
If the API Gateway is aware of the request and response models it can
Generate SDKs that include actual objects for each request and response rather than generic (JSON Object)
Allow JSON traversal of requests and responses in the data transformation engine
aws apigateway import-rest-api --body file://swagger.yaml
Map the API definition with the swagger file.
Show the swagger.yaml file.
- Show the credentials for auth and no-auth calls.
- Swagger normally defines only the user-facing details of an API
- We have extended it to also specify how the API processes a request and interacts with the backend
A single file allows you to create the entire API
http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions.html
x-amazon-apigateway-auth Object
x-amazon-apigateway-authorizer Object
x-amazon-apigateway-authtype Property
x-amazon-apigateway-integration Object
x-amazon-apigateway-integration.requestTemplates Object
x-amazon-apigateway-integration.requestParameters Object
x-amazon-apigateway-integration.responses Object
x-amazon-apigateway-integration.response Object
x-amazon-apigateway-integration.responseTemplates Object
x-amazon-apigateway-integration.responseParameters Object
We recommend to use some definition file (like Swagger), so you can ”own” the definition (create, document, version, etc) and the API Gateway is just the tool to implement the API.
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).
API can be imported and deployed in our build script.
Request routing and exceptions
No Infrastructure to manage: Focus on business logic, not infrastructure. You upload code; AWS Lambda handles everything else.
High performance at any scale; Cost-effective and efficient: Pay only for what you use: Lambda automatically matches capacity to your request rate. Purchase compute in 100ms increments.
Bring Your Own Code: Run code in a choice of standard languages. Use threads, processes, files, and shell scripts normally.
Show the transformation in the APIGW console
Show the Java Code (lambdaHandler) – RequestRouter.java
Show the actions code
Demo 2:
Start the App.
List the pets
Show DynamoDB, CloudWatch
Demo 3:
Create a new pet
Show DynamoDB, CloudWatch
Demo 4:
Login with an existing user, using CURL
Show CloudWatch
Demo 5:
Login with a non-existing user, using CURL
Notice the message and the status code: 400
Show CloudWatch
Show the code:
RequestRouter.java (line 48)
LoginDemoAction.java (line 75)
exception/BadRequestException.java (line 20)
configuration/ExceptionMessages.java (line 19)
Show API Gateway (mapping integration response)
Mapping templates are a powerful tool
Talk about variables ($input (json path, body, json, params), $context, $util (encode, decode, parsing, escape), $stageVariables)
Allows natively to use Apache Velocity Template Language (VTL) – use $util and $input.path to obtain an object representation (to use VTL on top of).
http://amzn.to/1L1hSF5
http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
Cognito: Identity Management Service (not an authentication service)
Identity management: Manage authenticated and guest users across identity providers (by assigning a unique identifier for each identity)
Secure AWS access: Securely access AWS services from mobile devices and platforms
Data synchronization: Synchronize users’ data across devices and platforms via the cloud
Demo 1:
Create a user using CURL
Show Cognito, DynamoDB, CloudWatch
We’ll go through a use case that leverage AWS Lambda and Amazon Cognito to retrieve temporary credentials for a particular end user and authorize access to the APIs
As discussed before the API Gateway helps customers leverage AWS Sigv4 – only one open API is required and then we can verify signatures on all other calls.
Show the code for LoginDemoAction.java
- Explain UserIdentity and UserCredentials objects (lines 85 and 86)
- Look at the code in provider/CognitoCredentialsProvider (UserIdentity in line 103 and UserCredentials in line 61)
Demo 4. Login with an existing user (via CURL)
Demo 2:
Open the App in the simulator (to do a query on the whole pet list)
Show CloudWatch logs.
Demo 2a:
Inside the App, look for the info on one of the pets
Show CloudWatch logs
We’ll go through a use case that leverage AWS Lambda and Amazon Cognito to retrieve temporary credentials for a particular end user and authorize access to the APIs
As discussed before the API Gateway helps customers leverage AWS Sigv4 – only one open API is required and then we can verify signatures on all other calls.
We’ll go through a use case that leverage AWS Lambda and Amazon Cognito to retrieve temporary credentials for a particular end user and authorize access to the APIs
As discussed before the API Gateway helps customers leverage AWS Sigv4 – only one open API is required and then we can verify signatures on all other calls.
See:
http://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html
Not-related sample of a FGAC policy (just to compare):
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1461416614573",
"Action": [ "dynamodb:DeleteItem" ],
"Effect": "Allow",
"Resource": "*",
"Condition": {
"StringEquals": { "dynamodb:LeadingKeys": "pet123”
}
}
}
]
}
API Gateway can generate client SDKs based on a customer’s API definition.
Simply select the deployment the SDK should target, the platform, and setup a couple of parameters and the API Gateway generates an SDK and makes it available to download through an API or the management console
SDK are model-aware and also come with the built-in AWS core that allows them to handle throttling responses and sign requests using AWS Credentials
Show APIGSessionCredentialsProvider.m (line 58)
Developer just needs to provide username + password, and the method will return the credentials
The method lazily load the credentials (the SDK just call the method when there is no valid stored credentials)
Show the code: AppDelegate.m (line 78)
The generated client SDK knows how to:
Sign API calls using AWS signature version 4
Handle-throttled responses with exponential back-off
Marshal and unmarshal requests and responses to model objects
First understand what has driven the decision to build API Gateway, from customer feedback to wider strategic decisions and market forces
Next, look at how the service works, and helps customers with their API services
Finally, open it out for Q&A at the end
Key Takeaways
AWS Lambda + Amazon API Gateway means no infrastructure to manage – we scale for you
Security is important, and complex – make the most of AWS Identity and Access Management. Security is a priority, take advantage of Authentication (Cognito) and Authorization (IAM) integration with API Gateway.
Swagger import and client SDK – we can automate most workflows