SlideShare a Scribd company logo
1 of 35
Mads Jensen
Protecting your APIs with
Doorkeeper and OAuth 2.0
aarhus.rb 11/04-2018
• SaaS business based in Silkeborg
• Loves Ruby on Rails
Definition
• “Who are you?”
• Establishing identity
• 401 Unauthorized
• “Can you do this?”
• Verifying access
• 403 Forbidden
Authentication Authorization
• Alternative to session cookies
• Embraces HTTP statelessness
• You don’t to have to worry about CSRF
• Ajax/SPA friendly
• Authorization: Bearer <token>
Token Based Authentication
API-first mindset
Your web appYour App
3rd party
cloud service
API
Part I: Introduction to
OAuth 2
Access Tokens Scopes ApplicationsRoles
Concepts
Access Tokens Scopes ApplicationsRoles
Concepts
Resource Owner Client Resource Server Authorization Server
“End-user” when
referring to a person
Capable of granting
access to protected
resource
The application
making
requests/accesses
the protected
resource on behalf
of the user
The server hosting
the protected
resource
The server issuing
access tokens to the
Client
Often same server
as the Resource
Server
Access Tokens
• Access tokens are often randomly generated strings,
opaque to the client
• Associated with a set of scopes
• Has a limited lifetime
• Can be made self contained with JWT
Scopes ApplicationsRoles
Concepts
Access Tokens Scopes ApplicationsRoles
Concepts
• Scopes define capabilities in your system
• Often divided in *_read and *_write
• Using scoped access token make it possible to create
levels of privileges
Access Tokens Scopes ApplicationsRoles
Concepts
• Represent a 3rd party
• Has client_id and client_secret
• Public or Confidential
• Must provide a Redirect URI
Protocol Overview
Client
(Application)
Owner
(End-user)
Auth Server
Resource
Server
Authorization request
Authorization grant
Authorization grant
Access Token
Access Token
Protected Resource
Authorization Prompt
Grant Types
Authorization Code Most used
Implicit Not recommended
Resource Owner
Password
Use only for 1st party
apps
Client Credentials
Lets the Application acts
on behalf of it self
Authorization Code Grant
Client
(Application)
Owner
(End-user)
Auth/Resource
Server
(Service API)
User-Agent
(Browser)
1. User Authorization Request
2. User Authorizes Application
3. Authorization Code Grant
4. Access Token Request
5. Access Token Grant
Endpoints
GET /authorize
Returns a human-friendly HTML page
with an “Authorize” and an “Decline”
button. Should somehow redirect user
POST /authorize
Used to obtain authorization grant via
user-agent redirect
POST /token
Used to exchange authorization grant
into access token
GET Client Redirect Endpoint
Where user-agent should redirect to after
/authorize
HTTP Requests
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.example.com
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
Server Client
• Token are issued with a limited life time
• Issued alongside access tokens
• Refresh tokens can be exchanged for new access tokens
• client_id and client_secret needed to refresh
• Uses the refresh_token grant type
Refresh tokens
Grants for Native Apps
• Possible to redirect from browser to native app, e.g.
webshipr://authorized
• Client secret cannot be used
• The Proof Key for Code Exchange (“pixie”) is an extension
to Authorization Code grant type
Grants for Native Apps
Source: The PKCE specification
Part II: Setting up
Doorkeeper
Doorkeeper
Defining Scopes
Protecting Controller
class BaseController < ActionController
before_action :doorkeeper_authorize!
end
Protecting Controller
class PostsController < BaseController
before_action -> {
doorkeeper_authorize! :read_posts
}, only: [:index, :show]
before_action -> {
doorkeeper_authorize! :write_posts
}, only: [:create, :delete, :update]
end
Handling User groups
• Business decision: Password grant tokens inherits scopes
from user group
• Business decision: Grant type authorization code can
elevate scopes
Handling User Groups
• Confirmation email on create
• Custom logic for password reset token and confirmation
email
• Special scope write_reset_password for setting password
Password Resets
Password Resets
Password Resets
• Test before_action validation with type: :request
• Test type: :controller with sign_in helper
Testing with RSpec
Testing with RSpec
Real world uses
• Email/password logins
• 1st party applications
• 3rd party applications
• Native applications
• Mobile apps
• API explorer in docs
The OAuth 2.0 Authorization Framework
https://tools.ietf.org/html/rfc6749
https://oauth.net/
An Introduction to OAuth 2
https://www.digitalocean.com/community/tutorials/an-introduction-to-
oauth-2
OAuth 2.0 Threat Model and Security Considerations
https://tools.ietf.org/html/rfc6819
Doorkeeper Github repo
https://github.com/doorkeeper-gem/doorkeeper
References
Questions?

More Related Content

What's hot

iPaaS: A platform for Integration technology convergence
iPaaS: A platform for Integration technology convergenceiPaaS: A platform for Integration technology convergence
iPaaS: A platform for Integration technology convergenceRaveendra Babu Darsi
 
Single sign on (SSO) How does your company apply?
Single sign on (SSO) How does your company apply?Single sign on (SSO) How does your company apply?
Single sign on (SSO) How does your company apply?Đỗ Duy Trung
 
Integrating FIDO Authentication & Federation Protocols
Integrating FIDO Authentication & Federation ProtocolsIntegrating FIDO Authentication & Federation Protocols
Integrating FIDO Authentication & Federation ProtocolsFIDO Alliance
 
Secure Spring Boot Microservices with Keycloak
Secure Spring Boot Microservices with KeycloakSecure Spring Boot Microservices with Keycloak
Secure Spring Boot Microservices with KeycloakRed Hat Developers
 
CQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationCQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationBrian Ritchie
 
Building an Effective Identity Management Strategy
Building an Effective Identity Management StrategyBuilding an Effective Identity Management Strategy
Building an Effective Identity Management StrategyNetIQ
 
Build Your Mobile App Faster with AWS Mobile Services (Cognito, Lambda, SNS, ...
Build Your Mobile App Faster with AWS Mobile Services (Cognito, Lambda, SNS, ...Build Your Mobile App Faster with AWS Mobile Services (Cognito, Lambda, SNS, ...
Build Your Mobile App Faster with AWS Mobile Services (Cognito, Lambda, SNS, ...Amazon Web Services
 
User Management Life Cycle with Keycloak
User Management Life Cycle with KeycloakUser Management Life Cycle with Keycloak
User Management Life Cycle with KeycloakMuhammad Edwin
 
俺が考えた最強のID連携デザインパターン
俺が考えた最強のID連携デザインパターン俺が考えた最強のID連携デザインパターン
俺が考えた最強のID連携デザインパターンMasaru Kurahayashi
 
Top 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | EdurekaTop 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | EdurekaEdureka!
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2Aaron Parecki
 
Balena: a Moby-based container engine for IoT
Balena: a Moby-based container engine for IoT Balena: a Moby-based container engine for IoT
Balena: a Moby-based container engine for IoT Balena
 
Designing APIs and Microservices Using Domain-Driven Design
Designing APIs and Microservices Using Domain-Driven DesignDesigning APIs and Microservices Using Domain-Driven Design
Designing APIs and Microservices Using Domain-Driven DesignLaunchAny
 
Azure conditional access
Azure conditional accessAzure conditional access
Azure conditional accessTad Yoke
 
Overview of Microsoft Teams and Data Loss Prevention(DLP)
Overview of Microsoft Teams  and Data Loss Prevention(DLP)Overview of Microsoft Teams  and Data Loss Prevention(DLP)
Overview of Microsoft Teams and Data Loss Prevention(DLP)Radhakrishnan Govindan
 

What's hot (20)

iPaaS: A platform for Integration technology convergence
iPaaS: A platform for Integration technology convergenceiPaaS: A platform for Integration technology convergence
iPaaS: A platform for Integration technology convergence
 
Single sign on (SSO) How does your company apply?
Single sign on (SSO) How does your company apply?Single sign on (SSO) How does your company apply?
Single sign on (SSO) How does your company apply?
 
Integrating FIDO Authentication & Federation Protocols
Integrating FIDO Authentication & Federation ProtocolsIntegrating FIDO Authentication & Federation Protocols
Integrating FIDO Authentication & Federation Protocols
 
Secure Spring Boot Microservices with Keycloak
Secure Spring Boot Microservices with KeycloakSecure Spring Boot Microservices with Keycloak
Secure Spring Boot Microservices with Keycloak
 
CQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility SegregationCQRS: Command/Query Responsibility Segregation
CQRS: Command/Query Responsibility Segregation
 
Building an Effective Identity Management Strategy
Building an Effective Identity Management StrategyBuilding an Effective Identity Management Strategy
Building an Effective Identity Management Strategy
 
Oauth2.0
Oauth2.0Oauth2.0
Oauth2.0
 
Build Your Mobile App Faster with AWS Mobile Services (Cognito, Lambda, SNS, ...
Build Your Mobile App Faster with AWS Mobile Services (Cognito, Lambda, SNS, ...Build Your Mobile App Faster with AWS Mobile Services (Cognito, Lambda, SNS, ...
Build Your Mobile App Faster with AWS Mobile Services (Cognito, Lambda, SNS, ...
 
Identity Management
Identity ManagementIdentity Management
Identity Management
 
User Management Life Cycle with Keycloak
User Management Life Cycle with KeycloakUser Management Life Cycle with Keycloak
User Management Life Cycle with Keycloak
 
Identity Access Management (IAM)
Identity Access Management (IAM)Identity Access Management (IAM)
Identity Access Management (IAM)
 
Spring Cloud Config
Spring Cloud ConfigSpring Cloud Config
Spring Cloud Config
 
俺が考えた最強のID連携デザインパターン
俺が考えた最強のID連携デザインパターン俺が考えた最強のID連携デザインパターン
俺が考えた最強のID連携デザインパターン
 
Top 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | EdurekaTop 50 Node.js Interview Questions and Answers | Edureka
Top 50 Node.js Interview Questions and Answers | Edureka
 
SSO introduction
SSO introductionSSO introduction
SSO introduction
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2
 
Balena: a Moby-based container engine for IoT
Balena: a Moby-based container engine for IoT Balena: a Moby-based container engine for IoT
Balena: a Moby-based container engine for IoT
 
Designing APIs and Microservices Using Domain-Driven Design
Designing APIs and Microservices Using Domain-Driven DesignDesigning APIs and Microservices Using Domain-Driven Design
Designing APIs and Microservices Using Domain-Driven Design
 
Azure conditional access
Azure conditional accessAzure conditional access
Azure conditional access
 
Overview of Microsoft Teams and Data Loss Prevention(DLP)
Overview of Microsoft Teams  and Data Loss Prevention(DLP)Overview of Microsoft Teams  and Data Loss Prevention(DLP)
Overview of Microsoft Teams and Data Loss Prevention(DLP)
 

Similar to Protecting your APIs with Doorkeeper and OAuth 2.0

Best Practices in Building an API Security Ecosystem
Best Practices in Building an API Security EcosystemBest Practices in Building an API Security Ecosystem
Best Practices in Building an API Security EcosystemPrabath Siriwardena
 
Learn with WSO2 - API Security
Learn with WSO2 - API Security Learn with WSO2 - API Security
Learn with WSO2 - API Security WSO2
 
Oauth2 and OWSM OAuth2 support
Oauth2 and OWSM OAuth2 supportOauth2 and OWSM OAuth2 support
Oauth2 and OWSM OAuth2 supportGaurav Sharma
 
What the Heck is OAuth and OIDC - UberConf 2018
What the Heck is OAuth and OIDC - UberConf 2018What the Heck is OAuth and OIDC - UberConf 2018
What the Heck is OAuth and OIDC - UberConf 2018Matt Raible
 
What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020
What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020
What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020Matt Raible
 
Securing APIs with OAuth 2.0
Securing APIs with OAuth 2.0Securing APIs with OAuth 2.0
Securing APIs with OAuth 2.0Kai Hofstetter
 
Oauth Nightmares Abstract OAuth Nightmares
Oauth Nightmares Abstract OAuth Nightmares Oauth Nightmares Abstract OAuth Nightmares
Oauth Nightmares Abstract OAuth Nightmares Nino Ho
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19aminmesbahi
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2Sanjoy Kumar Roy
 
Deep Dive into OAuth for Connected Apps
Deep Dive into OAuth for Connected AppsDeep Dive into OAuth for Connected Apps
Deep Dive into OAuth for Connected AppsSalesforce Developers
 
Protecting web APIs with OAuth 2.0
Protecting web APIs with OAuth 2.0Protecting web APIs with OAuth 2.0
Protecting web APIs with OAuth 2.0Vladimir Dzhuvinov
 
(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorization(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorizationanikristo
 
OAuth 2.0 and Library
OAuth 2.0 and LibraryOAuth 2.0 and Library
OAuth 2.0 and LibraryKenji Otsuka
 
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017Matt Raible
 
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...Vladimir Bychkov
 

Similar to Protecting your APIs with Doorkeeper and OAuth 2.0 (20)

Best Practices in Building an API Security Ecosystem
Best Practices in Building an API Security EcosystemBest Practices in Building an API Security Ecosystem
Best Practices in Building an API Security Ecosystem
 
Learn with WSO2 - API Security
Learn with WSO2 - API Security Learn with WSO2 - API Security
Learn with WSO2 - API Security
 
Oauth2 and OWSM OAuth2 support
Oauth2 and OWSM OAuth2 supportOauth2 and OWSM OAuth2 support
Oauth2 and OWSM OAuth2 support
 
What the Heck is OAuth and OIDC - UberConf 2018
What the Heck is OAuth and OIDC - UberConf 2018What the Heck is OAuth and OIDC - UberConf 2018
What the Heck is OAuth and OIDC - UberConf 2018
 
What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020
What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020
What the Heck is OAuth and OIDC - Denver Developer Identity Workshop 2020
 
Securing APIs with OAuth 2.0
Securing APIs with OAuth 2.0Securing APIs with OAuth 2.0
Securing APIs with OAuth 2.0
 
Oauth Nightmares Abstract OAuth Nightmares
Oauth Nightmares Abstract OAuth Nightmares Oauth Nightmares Abstract OAuth Nightmares
Oauth Nightmares Abstract OAuth Nightmares
 
OAuth2
OAuth2OAuth2
OAuth2
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19
 
OAuth2 + API Security
OAuth2 + API SecurityOAuth2 + API Security
OAuth2 + API Security
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2
 
Deep Dive into OAuth for Connected Apps
Deep Dive into OAuth for Connected AppsDeep Dive into OAuth for Connected Apps
Deep Dive into OAuth for Connected Apps
 
Protecting web APIs with OAuth 2.0
Protecting web APIs with OAuth 2.0Protecting web APIs with OAuth 2.0
Protecting web APIs with OAuth 2.0
 
(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorization(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorization
 
OAuth 2.0 and Library
OAuth 2.0 and LibraryOAuth 2.0 and Library
OAuth 2.0 and Library
 
O auth2.0 guide
O auth2.0 guideO auth2.0 guide
O auth2.0 guide
 
O auth 2
O auth 2O auth 2
O auth 2
 
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
 
OAuth2 Presentaion
OAuth2 PresentaionOAuth2 Presentaion
OAuth2 Presentaion
 
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...
2019 - Tech Talk DC - Token-based security for web applications using OAuth2 ...
 

Recently uploaded

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 

Recently uploaded (20)

What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 

Protecting your APIs with Doorkeeper and OAuth 2.0

  • 1. Mads Jensen Protecting your APIs with Doorkeeper and OAuth 2.0 aarhus.rb 11/04-2018
  • 2. • SaaS business based in Silkeborg • Loves Ruby on Rails
  • 3. Definition • “Who are you?” • Establishing identity • 401 Unauthorized • “Can you do this?” • Verifying access • 403 Forbidden Authentication Authorization
  • 4. • Alternative to session cookies • Embraces HTTP statelessness • You don’t to have to worry about CSRF • Ajax/SPA friendly • Authorization: Bearer <token> Token Based Authentication
  • 5. API-first mindset Your web appYour App 3rd party cloud service API
  • 6. Part I: Introduction to OAuth 2
  • 7. Access Tokens Scopes ApplicationsRoles Concepts
  • 8. Access Tokens Scopes ApplicationsRoles Concepts Resource Owner Client Resource Server Authorization Server “End-user” when referring to a person Capable of granting access to protected resource The application making requests/accesses the protected resource on behalf of the user The server hosting the protected resource The server issuing access tokens to the Client Often same server as the Resource Server
  • 9. Access Tokens • Access tokens are often randomly generated strings, opaque to the client • Associated with a set of scopes • Has a limited lifetime • Can be made self contained with JWT Scopes ApplicationsRoles Concepts
  • 10. Access Tokens Scopes ApplicationsRoles Concepts • Scopes define capabilities in your system • Often divided in *_read and *_write • Using scoped access token make it possible to create levels of privileges
  • 11. Access Tokens Scopes ApplicationsRoles Concepts • Represent a 3rd party • Has client_id and client_secret • Public or Confidential • Must provide a Redirect URI
  • 12. Protocol Overview Client (Application) Owner (End-user) Auth Server Resource Server Authorization request Authorization grant Authorization grant Access Token Access Token Protected Resource
  • 14. Grant Types Authorization Code Most used Implicit Not recommended Resource Owner Password Use only for 1st party apps Client Credentials Lets the Application acts on behalf of it self
  • 15. Authorization Code Grant Client (Application) Owner (End-user) Auth/Resource Server (Service API) User-Agent (Browser) 1. User Authorization Request 2. User Authorizes Application 3. Authorization Code Grant 4. Access Token Request 5. Access Token Grant
  • 16. Endpoints GET /authorize Returns a human-friendly HTML page with an “Authorize” and an “Decline” button. Should somehow redirect user POST /authorize Used to obtain authorization grant via user-agent redirect POST /token Used to exchange authorization grant into access token GET Client Redirect Endpoint Where user-agent should redirect to after /authorize
  • 17. HTTP Requests GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 Host: server.example.com POST /token HTTP/1.1 Host: server.example.com Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Content-Type: application/x-www-form-urlencoded grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb Server Client
  • 18. • Token are issued with a limited life time • Issued alongside access tokens • Refresh tokens can be exchanged for new access tokens • client_id and client_secret needed to refresh • Uses the refresh_token grant type Refresh tokens
  • 19. Grants for Native Apps • Possible to redirect from browser to native app, e.g. webshipr://authorized • Client secret cannot be used • The Proof Key for Code Exchange (“pixie”) is an extension to Authorization Code grant type
  • 20. Grants for Native Apps Source: The PKCE specification
  • 21. Part II: Setting up Doorkeeper
  • 24. Protecting Controller class BaseController < ActionController before_action :doorkeeper_authorize! end
  • 25. Protecting Controller class PostsController < BaseController before_action -> { doorkeeper_authorize! :read_posts }, only: [:index, :show] before_action -> { doorkeeper_authorize! :write_posts }, only: [:create, :delete, :update] end
  • 26. Handling User groups • Business decision: Password grant tokens inherits scopes from user group • Business decision: Grant type authorization code can elevate scopes
  • 28. • Confirmation email on create • Custom logic for password reset token and confirmation email • Special scope write_reset_password for setting password Password Resets
  • 31. • Test before_action validation with type: :request • Test type: :controller with sign_in helper Testing with RSpec
  • 33. Real world uses • Email/password logins • 1st party applications • 3rd party applications • Native applications • Mobile apps • API explorer in docs
  • 34. The OAuth 2.0 Authorization Framework https://tools.ietf.org/html/rfc6749 https://oauth.net/ An Introduction to OAuth 2 https://www.digitalocean.com/community/tutorials/an-introduction-to- oauth-2 OAuth 2.0 Threat Model and Security Considerations https://tools.ietf.org/html/rfc6819 Doorkeeper Github repo https://github.com/doorkeeper-gem/doorkeeper References

Editor's Notes

  1. Lad os først få et par begreber på plads. Autentifikation eller Autorisation Brug de engelske order for at holde et simpelt To forskellige begreber. Begge forkortet “Auth” Bemærk: HTTP Statuskoderne er ikke intuitive
  2. Et andet vigtigt begreb er Token Based Authentication, det er hele pointen med den her talk. Traditionelle websider bruger session cookies og CSRF tokens til at skabe Authentication mellem Clienten og Serveren. Session cookies bruger at abstrahere HTTP statelessness væk - men jeg synes at vi som udvikere burde omfavne alle HTTP’s egenskaber. Ved at abstrahere session cookies væk, glemmer man Authentication er en så vigtig del af web udvikling at man skal have styr på hvordan det fungerer. Bemærk: Og her betyder Auth Authentication og her skal man bruge headeren Authorization
  3. API-first betyder at man ser sin API som sin primære kilde til sin data og logik. Alt andet er applikationer der udnytter API. Web app’en kan være: 1) en single page app, der ikke bliver leveret fra samme server/service som API’en (som hos Webshipper) 2) Eller det kan være genereret HTML fra et klassisk Ruby on Rails projekt. Bemærk: Browseren kender ikke forskel på de to! (Bortset fra CORS og Ajax vs HTML forms) Ved en traditionel RoR projekt bruges session cookies til Authentication.
  4. OAuth2.0 er en protokol til at uddelegere tillid. Den bruger til at lade 3. parter tilgå en service (som regel en API) på vegne af en bruger. Single Click Signon and Apps til f.eks. Github er gode eksempler.
  5. De grundlæggende begreber
  6. OAuth2 definerer fire roller I protokollen: Resource Owner, Client, Resource Server, Auth server
  7. Access Tokens giver adgang til en beskyttet resource i et forudbestemt stykke tid. Often tilfældige tekst strenge.
  8. Scopes begrænser adgang til dine resource. Man lavet oftes en “read” og én “write” per resource type. Kan bruges til at lave brugergrupper med forskellige privilegier. Et godt supplement til gems som CanCanCan der kan give/begrænse adgang til enkelte records.
  9. Applications (også kalder Clients) er helt centrale i OAuth2. De beskriver en (oftes) 3.part der ønsker at tilgå din API (Protected Resource) på vegne af en af dine brugere. Udstyret med client_id og client_secret, tilfældige uid’er Skal være enten Public (SPA, Native, Mobile App) eller Confidential (Server backend). Skal beskrive én redirect URL Andet info: navn, logo, beskrivelse Kan have liste af hvilke scopes den kan tilgå
  10. OAuth består grundlæggende af 3 trin: Grant, Token exchange, Authenticated Request Et Grant giver I sig selv ikke adgang til Resource’n, men skal byttes til et Access Token. Auth og resource server er samlet, da de oftes er samme fysiske server De sidste to trin kan udføres så længe Access Token’en er gyldig Selvfølgelig: Så er intet af der her sikkert hvis man ikke bruger HTTPS! End-brugeren er kun involveret i trinnet “Authorization Grant”
  11. Brugeren giver sin tilladelse i en Authorization Prompt, her er det altså Auth Server’en der spørge Own’eren om Clienten på tilgå den beskyttede resource med de listede scopes. Eksempel: Fra Webshippers nye platform. 1st party app. 1st party apps kan godt spørge direkte efter usernavn/password, men dette sparer brugeren fra at taste.
  12. Grant types er måder for resource ejeren at give en 3rd part adgang De her hver deres brug scenarier Auth Code: Mest brugte Implicit: Best practice har ændret sig siden OAuth2 blev formuleret, anbefales ikke at bruge mere Resource Owner: Brugeren giver sit password væk, så kun for klient du virkelig stoler på Client Credentials: Client snakker med API’et uden at der er en bruge involveret Klik: Stjerne, Auth code mest anvendelige.
  13. Viser kun denne for at undgå information overload. Se OAuth2.0 standarden for detaljer om de andre. Dette er samme diagram som før, bare en implementation Bruger klikker på link, ledt hen på Authorization Prompt’en Bruger klikker Giv adgang HTTP redirect + 5 Server-til-Server kommunikation der bytter authorization code til access token Efter: Dette klienten kan bruge token’en til at tilgå resource’n
  14. For at få alt dette til at ske, skal kan oprette disse endpoints: OAuth2 specificere 3 endpoints: Authorization, Token og Client redirect end point POST /authorize er ikke krævet af protokollen, men benyttes næsten altid sådan
  15. I virkeligheden set det sådan ud. Først, et link til “server”, altså Authorization Serveren Bagefter: Redirect til client, “code” bliver sendt med som query parameter ved redirect “Authorization: Basic” er client id og client secret. Validerer clienten for ”confidential clients”
  16. Access Tokens har en begrænset levetid for at begrænse skaden hvis den bliver kompromiteret. En access token kan være sårbar overfor en dårlig HTTPS opsætning, exposure i server loggen eller ligne. Refresh tokens kan ombyttes til en access token. Det kan konfigureres om refresh tokens skal issues. I modsætning til access tokens udløber refresh tokens ikke, men kan blacklistes efter brug.
  17. Native apps bruger custom url schemas til i deres redirect urls, som f.eks. webshipr:// Native Apps er en form for Public Clients. Client secrets kan ikke gemmes i kompilet kildekode, det kan decompiles.
  18. Eksempel fra PKCE specifikation der viser hvordan et authorization code kan opsnappes på OS niveau. Advanceret angreb.
  19. Doorkeeper er en gem der implementerer OAuth2 i Ruby on Rails. Doorkeeper implementerer rollen som OAuth “Auth Server” “Resource Server” rollen er din service. Guiden ligger på Github siden og jeg vil ikke gennemgå den skridt for skridt. Det er bedst med “hands on”. Installation er ret ligetil: - kør rake task - kør migrations - opsæt routes
  20. Når doorkeeper er installeret så… I doorkeeper initializeren doorkeeper.rb. Vi har en del scopes, ca. 2 for hver resource I vores API. Se detaljer for andre configs i Doorkeepers dokumentation.
  21. For at beskytte sine controller skal man bruge doorkeeper_authorize! Kvæver at request har en gyldig token
  22. Denne controller kræver både at der eksiterer en gyldig token OG at read_posts/write_posts scopes existerer.
  23. Vi bruger doorkeeper til at lave email/password logins. Alle brugere tilhører én brugergruppe. For at holdet det enkelt har vi besluttet at tokens genereret med “resource owner password grant” skal arve scopes fra brugergruppen. Vi har også besluttet, for at undgå forvirring bland brugere, at brugere kan Authorize clienter selvom appen kræver scopes brugeren ikke har.
  24. Denne logik set sådan ud. Denne Controller overskriver den del af Doorkeeper der resolver hvilken Grant Type strategy der er tale om. Et passende sted at overskrive scopes inden en Access Token bliver genereret. Her bliver de request’ede scopes overskrevet med brugergruppens scopes.
  25. (Devise er en populær gem til håndtering af bruger authentication, her under signup, password reset.) Brugeren kan være i flere states: active, reset_requested, locked osv. Vi har valgt selv at implementere flowet omkring password resets og bruger oprettelse (samme logik) - Men det kan godt være muligt at bruge Devise. Vi bruger tokens til at tilgå vores API, derfor også til at resette password. Har var levet et specielt scope write_reset_password der kun giver tilladelse til dette.
  26. Vi genererer en token i maileren. Med en levetid på 4 timer Og så sender vi den til brugeren
  27. Når brugeren så trykker på linket Vi har oprettet en controller med én action der: Tjekker tokenen Tjekker om passwords matcher Sletter tokenen, for at undgå genbrug. Og så returnerer vi et success response
  28. Når man bruger spec types “request” kører rspec hele stakken igennem - ikke så meget magi, bare opret applications/brugere/osv. og send requests som specifikation foreskriver Typen “controller” mocker man typisk authentication ud med en “sign_in” helper
  29. sign_in helperen opretter: en UserGroup, med passende scopes (oftes alle mulige), kan tilpasses i en before block User og en Doorkeeper::AccessToken mocker tokenen på controlleren.
  30. Hvad kan man så bruge det her til? Indtil videre bruger vi OAuth2 til dette
  31. Anbefalet læsning