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("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)
. . . . . . . . . . . .
. . . . . . . . . .
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
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

ODP
Codegnitorppt
PDF
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...
DOCX
Microsoft identity platform and device authorization flow to use azure servic...
PPT
Form demoinplaywithmysql
PDF
Django の認証処理実装パターン / Django Authentication Patterns
PDF
Service Objects in Rails apps
PDF
Ajax Rails
 
KEY
IoC with PHP
Codegnitorppt
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...
Microsoft identity platform and device authorization flow to use azure servic...
Form demoinplaywithmysql
Django の認証処理実装パターン / Django Authentication Patterns
Service Objects in Rails apps
Ajax Rails
 
IoC with PHP

What's hot (7)

PPTX
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
PPTX
Introduction to OAuth
PDF
UI5CN Live Webinar for FAQ and Q&A on 08th June
PDF
devise tutorial - 2011 rubyconf taiwan
PDF
Medium TechTalk — iOS
PDF
From mvc to viper
PPTX
Angular Tutorial Freshers and Experienced
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
Introduction to OAuth
UI5CN Live Webinar for FAQ and Q&A on 08th June
devise tutorial - 2011 rubyconf taiwan
Medium TechTalk — iOS
From mvc to viper
Angular Tutorial Freshers and Experienced
Ad

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

PDF
Security enforcement of Java Microservices with Apiman & Keycloak
PPTX
API Workshop: Deep dive into REST APIs
PPT
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
PDF
Webauthn Tutorial
PPTX
Get started with building native mobile apps interacting with SharePoint
PDF
SoftLayer API 12032015
PDF
How to build an AngularJS backend-ready app WITHOUT BACKEND
PPT
Symfony2 and AngularJS
PPTX
Vue.js + Django - configuración para desarrollo con webpack y HMR
PDF
Exploring MORE Google (Cloud) APIs with Python
PDF
A Detailed Guide to Securing React applications with Keycloak - WalkingTree ...
PPTX
Deploying your static web app to the Cloud
PPTX
SharePoint and Office Development Workshop
PPTX
Securing RESTful APIs using OAuth 2 and OpenID Connect
PPTX
Designing CakePHP plugins for consuming APIs
PDF
How to Implement Token Authentication Using the Django REST Framework
PPTX
Method and decorator
ZIP
Palestra VCR
PDF
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
PDF
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...
Security enforcement of Java Microservices with Apiman & Keycloak
API Workshop: Deep dive into REST APIs
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
Webauthn Tutorial
Get started with building native mobile apps interacting with SharePoint
SoftLayer API 12032015
How to build an AngularJS backend-ready app WITHOUT BACKEND
Symfony2 and AngularJS
Vue.js + Django - configuración para desarrollo con webpack y HMR
Exploring MORE Google (Cloud) APIs with Python
A Detailed Guide to Securing React applications with Keycloak - WalkingTree ...
Deploying your static web app to the Cloud
SharePoint and Office Development Workshop
Securing RESTful APIs using OAuth 2 and OpenID Connect
Designing CakePHP plugins for consuming APIs
How to Implement Token Authentication Using the Django REST Framework
Method and decorator
Palestra VCR
JavaScript & Cloud: the AWS JS SDK and how to work with cloud resources
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...
Ad

More from Provectus (20)

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

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PPTX
A Presentation on Artificial Intelligence
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Approach and Philosophy of On baking technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
cuic standard and advanced reporting.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
Teaching material agriculture food technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Encapsulation theory and applications.pdf
Machine learning based COVID-19 study performance prediction
A Presentation on Artificial Intelligence
Chapter 3 Spatial Domain Image Processing.pdf
Empathic Computing: Creating Shared Understanding
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Approach and Philosophy of On baking technology
Unlocking AI with Model Context Protocol (MCP)
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Review of recent advances in non-invasive hemoglobin estimation
cuic standard and advanced reporting.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Teaching material agriculture food technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
The AUB Centre for AI in Media Proposal.docx
Network Security Unit 5.pdf for BCA BBA.
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Spectroscopy.pptx food analysis technology
Encapsulation theory and applications.pdf

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://<ip name>: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 <AppId> http://<server>/authenticate Blah-blah-Debug {"auth_token":"eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NTk5OTYyMjZ9.H9zjYGAIUwBZY 5Kb3KlF9eegTph9GmBBbLNrki1450U"} curl -H "Authorization: eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NTk5OTYyMjZ9.H9zjYGAIUwBZY5Kb3KlF9eegT ph9GmBBbLNrki1450U" http://<server>: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: "<Your role ARN here arn:aws:iam::xxxx:role/role-name") rails s -b 0.0.0.0 3000
  • 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": "<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"}
  • 22. Q&A