SlideShare a Scribd company logo
How to implement authorization
in your backend with AWS IAM
About me
- 14 years in industry
- DevOps Consultant at Provectus
stanislav@ivashchenko.family
Stanislav
Ivashchenko
DevOps Lead
Boost your career
in Provectus
Typical app these days: many players
https://commons.wikimedia.org/wiki/File:Pride_and_Prejudice_Character_Map.png
2 Questions for backend
● Service discovery
● Credentials
Login to your application
A new service starts up, where to get credentials?
1. Bake into ami or docker image or use a hardcode?
2. Provision with Chef/Puppet/Ansible/script over ssh?
3. Get from s3 bucket?
4. Parameter Store?
5. Vault?
6. Surprisingly many more ways, actually!
7. The questions is absolutely the same for any code you run: EC2,
Lambda, ECS
S3, Parameter Store, Vault
But how do you login there in the first place?
Ah, IAM instance profiles!
Inspired by how Vault authenticates users
https://www.hashicorp.com/resources/deep-dive-vault-aws-auth-backend
But why use Vault or Parameter Store, go
directly with IAM and STS
WhoAmI Request on STS
● This is a cornerstone of the entire idea
● Such request actually exists: sts:GetCallerIdentity
● Signed requests live for 15 min
● Discussed https://github.com/hashicorp/vault/issues/948
● Implemented in Vault https://github.com/hashicorp/vault/pull/1962
MiM used for good with STS
Example implementation
● API server - simple RoR api
● Client - python script
● https://github.com/sam50/ror_aws_iam_auth
● 2 instances, client has an EC2 instance profile with role
What Client is doing
1. Generates signed STS GetCallerIdentity request
2. Sends it to server http://<ip name>:3000/authenticate
3. Gets JWT Auth token
4. Uses that token to do things in API
def generate_sts_request(AppId):
session = botocore.session.get_session()
client = session.create_client('sts')
endpoint = client._endpoint
operation_model = client._service_model.operation_model('GetCallerIdentity')
request_dict = client._convert_to_request_dict({}, operation_model)
request_dict['headers']['X-APP-ID'] = AppId
request = endpoint.create_request(request_dict, operation_model)
return {
'iam_http_request_method': base64.b64encode(request.method),
'iam_request_url': base64.b64encode(request.url),
'iam_request_body': base64.b64encode(request.body),
'iam_request_headers': base64.b64encode(json.dumps(dict(request.headers))),
}
$ ./api_client.py <AppId> http://<server>/authenticate
Blah-blah-Debug
{"auth_token":"eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NTk5OTYyMjZ9.H9zjYGAIUwBZY
5Kb3KlF9eegTph9GmBBbLNrki1450U"}
curl -H "Authorization:
eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NTk5OTYyMjZ9.H9zjYGAIUwBZY5Kb3KlF9eegT
ph9GmBBbLNrki1450U" http://<server>:3000/items
What server is doing
1. A simple API ($rails new api1 --api)
2. Uses a JWT (gem 'jwt')
3. Uses simple command(gem 'simple_command')
4. Receives login(signed sts:GetCallerIdentity) at /authenticate
5. Sends signed request to STS*
6. (if-ok) Looks for the user by the Role ARN
7. (if-ok) issues a JWT token to the client
def authenticate_iam
uri = URI.parse(
. . . . . . . . . .
if response.code != '200' || response.body.empty?
return false
else
xml = Nokogiri::XML(response.body)
stsarn = xml.remove_namespaces!.xpath(
git clone https://github.com/sam50/ror_aws_iam_auth
cd ror_aws_iam_auth
bundle install
rake db:migrate
rails c
>User.create!(name:"client1", iamarn: "<Your role ARN here
arn:aws:iam::xxxx:role/role-name")
rails s -b 0.0.0.0 3000
Signed Request (b64Decoded)
{"iam_request_body": "Action=GetCallerIdentity&Version=2011-06-15",
"iam_request_url": "https://sts.amazonaws.com/",
"iam_request_headers": "{"Content-Length": "X","X-Amz-Date": "X", "X-APP-ID": "AppId", "User-
Agent": "Botocore/1.12.139 Python/2.7.15rc1 Linux/4.15.0-1032-aws", "X-Amz-Security-Token":
"<Token>", "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", "Authorization":
"AWS4-HMAC-SHA256 Credential=<CredsID>, SignedHeaders=content-type;host;x-amz-date;x-amz-
security-token;x-app-id, Signature=<Signiture>"}", "iam_http_request_method": "POST"}
Q&A
Thank you!
We are hiring!

More Related Content

What's hot (7)

AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
murtazahaveliwala
 
Introduction to OAuth
Introduction to OAuth
Mikkel Flindt Heisterberg
 
UI5CN Live Webinar for FAQ and Q&A on 08th June
UI5CN Live Webinar for FAQ and Q&A on 08th June
AJAY NAYAK
 
devise tutorial - 2011 rubyconf taiwan
devise tutorial - 2011 rubyconf taiwan
Tse-Ching Ho
 
Medium TechTalk — iOS
Medium TechTalk — iOS
jimmyatmedium
 
From mvc to viper
From mvc to viper
Krzysztof Profic
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
rajkamaltibacademy
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
murtazahaveliwala
 
UI5CN Live Webinar for FAQ and Q&A on 08th June
UI5CN Live Webinar for FAQ and Q&A on 08th June
AJAY NAYAK
 
devise tutorial - 2011 rubyconf taiwan
devise tutorial - 2011 rubyconf taiwan
Tse-Ching Ho
 
Medium TechTalk — iOS
Medium TechTalk — iOS
jimmyatmedium
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
rajkamaltibacademy
 

Similar to How to implement authorization in your backend with AWS IAM (20)

Security enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & Keycloak
Charles Moulliard
 
API Workshop: Deep dive into REST APIs
API Workshop: Deep dive into REST APIs
Tom Johnson
 
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
Kiril Iliev
 
Webauthn Tutorial
Webauthn Tutorial
FIDO Alliance
 
Get started with building native mobile apps interacting with SharePoint
Get started with building native mobile apps interacting with SharePoint
Yaroslav Pentsarskyy [MVP]
 
SoftLayer API 12032015
SoftLayer API 12032015
Nacho Daza
 
How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND
Enrique Oriol Bermúdez
 
Symfony2 and AngularJS
Symfony2 and AngularJS
Antonio Peric-Mazar
 
Vue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMR
Javier Abadía
 
Exploring MORE Google (Cloud) APIs with Python
Exploring MORE Google (Cloud) APIs with Python
wesley chun
 
A Detailed Guide to Securing React applications with Keycloak - WalkingTree ...
A Detailed Guide to Securing React applications with Keycloak - WalkingTree ...
Ganesh Kumar
 
Deploying your static web app to the Cloud
Deploying your static web app to the Cloud
Christoffer Noring
 
SharePoint and Office Development Workshop
SharePoint and Office Development Workshop
Eric Shupps
 
Securing RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID Connect
Jonathan LeBlanc
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIs
Neil Crookes
 
How to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST Framework
Katy Slemon
 
Method and decorator
Method and decorator
Celine George
 
Palestra VCR
Palestra VCR
Cássio Marques
 
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
Corley S.r.l.
 
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...
Andrey Devyatkin
 
Security enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & Keycloak
Charles Moulliard
 
API Workshop: Deep dive into REST APIs
API Workshop: Deep dive into REST APIs
Tom Johnson
 
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
Kiril Iliev
 
Get started with building native mobile apps interacting with SharePoint
Get started with building native mobile apps interacting with SharePoint
Yaroslav Pentsarskyy [MVP]
 
SoftLayer API 12032015
SoftLayer API 12032015
Nacho Daza
 
How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND
Enrique Oriol Bermúdez
 
Vue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMR
Javier Abadía
 
Exploring MORE Google (Cloud) APIs with Python
Exploring MORE Google (Cloud) APIs with Python
wesley chun
 
A Detailed Guide to Securing React applications with Keycloak - WalkingTree ...
A Detailed Guide to Securing React applications with Keycloak - WalkingTree ...
Ganesh Kumar
 
Deploying your static web app to the Cloud
Deploying your static web app to the Cloud
Christoffer Noring
 
SharePoint and Office Development Workshop
SharePoint and Office Development Workshop
Eric Shupps
 
Securing RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID Connect
Jonathan LeBlanc
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIs
Neil Crookes
 
How to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST Framework
Katy Slemon
 
Method and decorator
Method and decorator
Celine George
 
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
Corley S.r.l.
 
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...
Andrey Devyatkin
 
Ad

More from Provectus (20)

Choosing the right IDP Solution
Choosing the right IDP Solution
Provectus
 
Intelligent Document Processing in Healthcare. Choosing the Right Solutions.
Intelligent Document Processing in Healthcare. Choosing the Right Solutions.
Provectus
 
Choosing the Right Document Processing Solution for Healthcare Organizations
Choosing the Right Document Processing Solution for Healthcare Organizations
Provectus
 
MLOps and Data Quality: Deploying Reliable ML Models in Production
MLOps and Data Quality: Deploying Reliable ML Models in Production
Provectus
 
AI Stack on AWS: Amazon SageMaker and Beyond
AI Stack on AWS: Amazon SageMaker and Beyond
Provectus
 
Feature Store as a Data Foundation for Machine Learning
Feature Store as a Data Foundation for Machine Learning
Provectus
 
MLOps and Reproducible ML on AWS with Kubeflow and SageMaker
MLOps and Reproducible ML on AWS with Kubeflow and SageMaker
Provectus
 
Cost Optimization for Apache Hadoop/Spark Workloads with Amazon EMR
Cost Optimization for Apache Hadoop/Spark Workloads with Amazon EMR
Provectus
 
ODSC webinar "Kubeflow, MLFlow and Beyond — augmenting ML delivery" Stepan Pu...
ODSC webinar "Kubeflow, MLFlow and Beyond — augmenting ML delivery" Stepan Pu...
Provectus
 
"Building a Modern Data platform in the Cloud", Alex Casalboni, AWS Dev Day K...
"Building a Modern Data platform in the Cloud", Alex Casalboni, AWS Dev Day K...
Provectus
 
"How to build a global serverless service", Alex Casalboni, AWS Dev Day Kyiv ...
"How to build a global serverless service", Alex Casalboni, AWS Dev Day Kyiv ...
Provectus
 
"Automating AWS Infrastructure with PowerShell", Martin Beeby, AWS Dev Day Ky...
"Automating AWS Infrastructure with PowerShell", Martin Beeby, AWS Dev Day Ky...
Provectus
 
"Analyzing your web and application logs", Javier Ramirez, AWS Dev Day Kyiv 2...
"Analyzing your web and application logs", Javier Ramirez, AWS Dev Day Kyiv 2...
Provectus
 
"Resiliency and Availability Design Patterns for the Cloud", Sebastien Storma...
"Resiliency and Availability Design Patterns for the Cloud", Sebastien Storma...
Provectus
 
"Architecting SaaS solutions on AWS", Oleksandr Mykhalchuk, AWS Dev Day Kyiv ...
"Architecting SaaS solutions on AWS", Oleksandr Mykhalchuk, AWS Dev Day Kyiv ...
Provectus
 
"Developing with .NET Core on AWS", Martin Beeby, AWS Dev Day Kyiv 2019
"Developing with .NET Core on AWS", Martin Beeby, AWS Dev Day Kyiv 2019
Provectus
 
"How to build real-time backends", Martin Beeby, AWS Dev Day Kyiv 2019
"How to build real-time backends", Martin Beeby, AWS Dev Day Kyiv 2019
Provectus
 
"Integrate your front end apps with serverless backend in the cloud", Sebasti...
"Integrate your front end apps with serverless backend in the cloud", Sebasti...
Provectus
 
"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019
"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019
Provectus
 
Yurii Gavrilin | ML Interpretability: From A to Z | Kazan ODSC Meetup
Yurii Gavrilin | ML Interpretability: From A to Z | Kazan ODSC Meetup
Provectus
 
Choosing the right IDP Solution
Choosing the right IDP Solution
Provectus
 
Intelligent Document Processing in Healthcare. Choosing the Right Solutions.
Intelligent Document Processing in Healthcare. Choosing the Right Solutions.
Provectus
 
Choosing the Right Document Processing Solution for Healthcare Organizations
Choosing the Right Document Processing Solution for Healthcare Organizations
Provectus
 
MLOps and Data Quality: Deploying Reliable ML Models in Production
MLOps and Data Quality: Deploying Reliable ML Models in Production
Provectus
 
AI Stack on AWS: Amazon SageMaker and Beyond
AI Stack on AWS: Amazon SageMaker and Beyond
Provectus
 
Feature Store as a Data Foundation for Machine Learning
Feature Store as a Data Foundation for Machine Learning
Provectus
 
MLOps and Reproducible ML on AWS with Kubeflow and SageMaker
MLOps and Reproducible ML on AWS with Kubeflow and SageMaker
Provectus
 
Cost Optimization for Apache Hadoop/Spark Workloads with Amazon EMR
Cost Optimization for Apache Hadoop/Spark Workloads with Amazon EMR
Provectus
 
ODSC webinar "Kubeflow, MLFlow and Beyond — augmenting ML delivery" Stepan Pu...
ODSC webinar "Kubeflow, MLFlow and Beyond — augmenting ML delivery" Stepan Pu...
Provectus
 
"Building a Modern Data platform in the Cloud", Alex Casalboni, AWS Dev Day K...
"Building a Modern Data platform in the Cloud", Alex Casalboni, AWS Dev Day K...
Provectus
 
"How to build a global serverless service", Alex Casalboni, AWS Dev Day Kyiv ...
"How to build a global serverless service", Alex Casalboni, AWS Dev Day Kyiv ...
Provectus
 
"Automating AWS Infrastructure with PowerShell", Martin Beeby, AWS Dev Day Ky...
"Automating AWS Infrastructure with PowerShell", Martin Beeby, AWS Dev Day Ky...
Provectus
 
"Analyzing your web and application logs", Javier Ramirez, AWS Dev Day Kyiv 2...
"Analyzing your web and application logs", Javier Ramirez, AWS Dev Day Kyiv 2...
Provectus
 
"Resiliency and Availability Design Patterns for the Cloud", Sebastien Storma...
"Resiliency and Availability Design Patterns for the Cloud", Sebastien Storma...
Provectus
 
"Architecting SaaS solutions on AWS", Oleksandr Mykhalchuk, AWS Dev Day Kyiv ...
"Architecting SaaS solutions on AWS", Oleksandr Mykhalchuk, AWS Dev Day Kyiv ...
Provectus
 
"Developing with .NET Core on AWS", Martin Beeby, AWS Dev Day Kyiv 2019
"Developing with .NET Core on AWS", Martin Beeby, AWS Dev Day Kyiv 2019
Provectus
 
"How to build real-time backends", Martin Beeby, AWS Dev Day Kyiv 2019
"How to build real-time backends", Martin Beeby, AWS Dev Day Kyiv 2019
Provectus
 
"Integrate your front end apps with serverless backend in the cloud", Sebasti...
"Integrate your front end apps with serverless backend in the cloud", Sebasti...
Provectus
 
"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019
"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019
Provectus
 
Yurii Gavrilin | ML Interpretability: From A to Z | Kazan ODSC Meetup
Yurii Gavrilin | ML Interpretability: From A to Z | Kazan ODSC Meetup
Provectus
 
Ad

Recently uploaded (20)

cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 

How to implement authorization in your backend with AWS IAM

  • 1. How to implement authorization in your backend with AWS IAM
  • 2. About me - 14 years in industry - DevOps Consultant at Provectus [email protected] Stanislav Ivashchenko DevOps Lead
  • 4. Typical app these days: many players https://commons.wikimedia.org/wiki/File:Pride_and_Prejudice_Character_Map.png
  • 5. 2 Questions for backend ● Service discovery ● Credentials
  • 6. Login to your application
  • 7. A new service starts up, where to get credentials? 1. Bake into ami or docker image or use a hardcode? 2. Provision with Chef/Puppet/Ansible/script over ssh? 3. Get from s3 bucket? 4. Parameter Store? 5. Vault? 6. Surprisingly many more ways, actually! 7. The questions is absolutely the same for any code you run: EC2, Lambda, ECS
  • 8. S3, Parameter Store, Vault But how do you login there in the first place? Ah, IAM instance profiles!
  • 9. Inspired by how Vault authenticates users https://www.hashicorp.com/resources/deep-dive-vault-aws-auth-backend
  • 10. But why use Vault or Parameter Store, go directly with IAM and STS
  • 11. WhoAmI Request on STS ● This is a cornerstone of the entire idea ● Such request actually exists: sts:GetCallerIdentity ● Signed requests live for 15 min ● Discussed https://github.com/hashicorp/vault/issues/948 ● Implemented in Vault https://github.com/hashicorp/vault/pull/1962
  • 12. MiM used for good with STS
  • 13. Example implementation ● API server - simple RoR api ● Client - python script ● https://github.com/sam50/ror_aws_iam_auth ● 2 instances, client has an EC2 instance profile with role
  • 14. What Client is doing 1. Generates signed STS GetCallerIdentity request 2. Sends it to server http://:3000/authenticate 3. Gets JWT Auth token 4. Uses that token to do things in API
  • 15. def generate_sts_request(AppId): session = botocore.session.get_session() client = session.create_client('sts') endpoint = client._endpoint operation_model = client._service_model.operation_model('GetCallerIdentity') request_dict = client._convert_to_request_dict({}, operation_model) request_dict['headers']['X-APP-ID'] = AppId request = endpoint.create_request(request_dict, operation_model) return { 'iam_http_request_method': base64.b64encode(request.method), 'iam_request_url': base64.b64encode(request.url), 'iam_request_body': base64.b64encode(request.body), 'iam_request_headers': base64.b64encode(json.dumps(dict(request.headers))), }
  • 16. $ ./api_client.py http:///authenticate Blah-blah-Debug {"auth_token":"eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NTk5OTYyMjZ9.H9zjYGAIUwBZY 5Kb3KlF9eegTph9GmBBbLNrki1450U"} curl -H "Authorization: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NTk5OTYyMjZ9.H9zjYGAIUwBZY5Kb3KlF9eegT ph9GmBBbLNrki1450U" http://:3000/items
  • 17. What server is doing 1. A simple API ($rails new api1 --api) 2. Uses a JWT (gem 'jwt') 3. Uses simple command(gem 'simple_command') 4. Receives login(signed sts:GetCallerIdentity) at /authenticate 5. Sends signed request to STS* 6. (if-ok) Looks for the user by the Role ARN 7. (if-ok) issues a JWT token to the client
  • 18. def authenticate_iam uri = URI.parse("https://sts.amazonaws.com/") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = "Net::HTTP::#{@iam_http_request_method.capitalize}".constantize.new(uri.request_uri) request.set_form_data(Rack::Utils.parse_nested_query(@iam_request_body)) headers = JSON.parse(@iam_request_headers) headers.each do |header, value| request[header]=value end if headers['X-APP-ID'] != 'APP1-live' return false end response = http.request(request) . . . . . . . . . . . .
  • 19. . . . . . . . . . . if response.code != '200' || response.body.empty? return false else xml = Nokogiri::XML(response.body) stsarn = xml.remove_namespaces!.xpath("GetCallerIdentityResponse/GetCallerIdentityResult/Arn").text if stsarn.empty? return false else return stsarn.gsub("arn:aws:sts","arn:aws:iam").gsub("assumed-role","role").gsub(//[A-z0-9-]*$/,"") end end return false end
  • 20. git clone https://github.com/sam50/ror_aws_iam_auth cd ror_aws_iam_auth bundle install rake db:migrate rails c >User.create!(name:"client1", iamarn: "
  • 21. Signed Request (b64Decoded) {"iam_request_body": "Action=GetCallerIdentity&Version=2011-06-15", "iam_request_url": "https://sts.amazonaws.com/", "iam_request_headers": "{"Content-Length": "X","X-Amz-Date": "X", "X-APP-ID": "AppId", "User- Agent": "Botocore/1.12.139 Python/2.7.15rc1 Linux/4.15.0-1032-aws", "X-Amz-Security-Token": "", "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", "Authorization": "AWS4-HMAC-SHA256 Credential=, SignedHeaders=content-type;host;x-amz-date;x-amz- security-token;x-app-id, Signature="}", "iam_http_request_method": "POST"}
  • 22. Q&A