SlideShare una empresa de Scribd logo
1 de 44
Descargar para leer sin conexión
OAuth 2.0
A standard is coming of age
Uwe Friedrichsen, codecentric AG, 2013
Uwe Friedrichsen
@ufried
<session>
<no-code>
<motivation />
<history />
<solution />
<extensions />
<criticism />
<tips />
</no-code>
<code>
<authzorization />
<token />
<resource />
</code>
<wrap-up />
</session>
{ „session“ : {
„no-code“ : [
„motivation“,
„history“,
„solution“,
„extensions“,
„criticism“,
„tips“
],
„code“ : [
„authorization“,
„token“,
„resource“
],
„wrap-up“ : true
}
Players
You
Application with
protected resources
Another
application
Assignment
You
Application with
protected resources
Another
application
Access your resources
Problem
You
Application with
protected resources
Another
application
Access your resources
Challenge
You
Application with
protected resources
Another
application
Access your resources
Secure
?Easy to use
OAuth 1.0
• Started by Twitter in 2006
• 1st Draft Standard in 10/2007
• IETF RFC 5849 in 4/2010
• Widespread
• Complex Client Security Handling
• Limited Scope
• Not extendable
• Not „Enterprise-ready“
OAuth 2.0
• Working Group started 4/2010
• 31 Draft Versions
• Eran Hammer-Lahav left 7/2012 *
• IETF RFC 6749 in 10/2012
* http://hueniverse.com/2012/07/
oauth-2-0-and-the-road-to-hell/
You
Application with
protected resources
Another
application
Players revisited
Players revisited
You Authorization
Server
Client
Application
Resource
Server
Solution (Step 1)
You Authorization
Server
Client
Application
Resource
Server
1. I want an
authorization
code
4. Here is an authorization code for client XYZ
3. User: „Yes, it‘s okay“
2.Client XYZ wants an authorization code
5. Here you are
Solution (Step 2)
You Authorization
Server
Client
Application
Resource
Server
7. Here you are
6. I want to trade my
authorization code
for an access token
Solution (Step 3)
You Authorization
Server
Client
Application
Resource
Server
Give me some resources.
Here is my access token, btw.
…
A few more
Details
• TLS/SSL
• Endpoints
• Client Types
• Client Identifier
• Client Authentication
• Redirect URI
• Access Token Scope
• Refresh Token
• Client State
You Authorization
Server
Client
Application
Resource
Server
1. I want an
authorization
code
4. Here is an authorization code for client XYZ
3. User: „Yes, it‘s okay“
2.Client XYZ wants an authorization code
5. Here you areGET /authorize?
response_type=code&
client_id=s6BhdRkqt3&
state=xyz&
redirect_uri=https%3A%2F%2Fclient%2E
example%2Ecom%2Fcb HTTP/1.1
Host: server.example.com
You Authorization
Server
Client
Application
Resource
Server
1. I want an
authorization
code
4. Here is an authorization code for client XYZ
3. User: „Yes, it‘s okay“
2.Client XYZ wants an authorization code
5. Here you are
HTTP/1.1 302 Found
Location: 
https://client.example.com/cb?
code=SplxlOBeZQQYbYS6WxSbIA&
state=xyz
You Authorization
Server
Client
Application
Resource
Server
7. Here you are
6. I want to trade my
authorization code
for an access token
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
You Authorization
Server
Client
Application
Resource
Server
7. Here you are
6. I want to trade my
authorization code
for an access token
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"
}
You Authorization
Server
Client
Application
Resource
Server
Give me some resources.
Here is my access token, btw.
…
GET /resource/1 HTTP/1.1
Host: example.com
Authorization: Bearer 2YotnFZFEjr1zCsicMWpAA
More flows &
Extensions
• Implicit Grant
• Resource Owner Password
Credentials Grant
• Client Credentials Grant
• Refresh Token Grant
• Standard & custom Extensions
• Standards based on OAuth 2.0
Criticism
• Too many compromises
• No built-in security
• Relies solely on SSL
• Bearer Token
• Self-encrypted token
Tips
• Turn MAY into MUST
• Use HMAC Tokens
• Use HMAC to sign Content
• No self-encrypted token
• Always check the SSL Certificate
How does the
code feel like?
using Apache Amber 0.22
You Authorization
Server
Client
Application
Resource
Server
1. I want an
authorization
code
4. Here is an authorization code for client XYZ
3. User: „Yes, it‘s okay“
2.Client XYZ wants an authorization code
5. Here you areGET /authorize?
response_type=code&
client_id=s6BhdRkqt3&
state=xyz&
redirect_uri=https%3A%2F%2Fclient%2E
example%2Ecom%2Fcb HTTP/1.1
Host: server.example.com
Authorization Endpoint (1)
@Path("/authorize")
public class AuthorizationEndpoint {
@Context
private SecurityDataStore securityDataStore;
@GET
@Consumes(OAuth.ContentType.URL_ENCODED)
public Response authorize(@Context HttpServletRequest request) {
// Do the required validations
OAuthAuthzRequest oauthRequest = wrapAndValidate(request);
validateRedirectionURI(oauthRequest);
// Actual authentication not defined by OAuth 2.0
// Here a forward to a login page is used
String loginURI = buildLoginURI(oauthRequest);
return Response.status(HttpServletResponse.SC_FOUND)
.location(new URI(loginUri)).build();
}
...
Authorization Endpoint (2)
...
private OAuthAuthzRequest wrapAndValidate(HttpServletRequest req) {
// Implicitly validates the request locally
return new OAuthAuthzRequest(req);
}
...
Authorization Endpoint (3)
...
private void validateRedirectionURI(OAuthAuthzRequest oauthReq) {
String redirectionURISent = oauthReq.getRedirectURI();
String redirectionURIStored = securityDataStore
.getRedirectUriForClient(oauthReq.getClientId());
if (!redirectionURIStored
.equalsIgnoreCase(redirectionURISent)) {
OAuthProblemException oAuthProblem =
OAuthProblemException
.error(OAuthError.CodeResponse.ACCESS_DENIED,
"Invalid Redirection URI");
oAuthProblem.setRedirectUri(redirectionURISent);
throw oAuthProblem;
}
}
...
Authorization Endpoint (4)
...
private String buildLoginURI(OAuthAuthzRequest oauthRequest) {
String loginURI = getBaseLoginURI(); // As an example
loginURI += "&" + OAuth.OAUTH_RESPONSE_TYPE + "=“
+ oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
loginURI += "?" + OAuth.OAUTH_CLIENT_ID + "=“
+ oauthRequest.getClientId();
loginURI += "&" + OAuth.OAUTH_REDIRECT_URI + "=“
+ redirectUri;
loginURI += "&" + OAuth.OAUTH_SCOPE + "=“
+ getParam(OAuth.OAUTH_SCOPE);
loginURI += "&" + OAuth.OAUTH_STATE + "=“
+ getParam(OAuth.OAUTH_STATE);
return loginURI;
}
}
You Authorization
Server
Client
Application
Resource
Server
1. I want an
authorization
code
4. Here is an authorization code for client XYZ
3. User: „Yes, it‘s okay“
2.Client XYZ wants an authorization code
5. Here you are
HTTP/1.1 302 Found
Location: 
https://client.example.com/cb?
code=SplxlOBeZQQYbYS6WxSbIA&
state=xyz
Login page handler
private void getAndSendAuthorizationCode(HttpServletRequest req,
HttpServletResponse resp) {
// Assuming login was successful and forwarded
// parameters can be found in the request
String userId = (String) request.getAttribute("userId");
String clientId =
(String) request.getAttribute(OAuth.OAUTH_CLIENT_ID);
// Create a new authorization code and store it in the database
String authzCode =
securityDataStore.getAuthorizationCode(userId, clientId);
// Redirect back to client
String redirectUri =
(String) req.getAttribute(OAuth.OAUTH_REDIRECT_URI);
redirectUri += "?" + OAuth.OAUTH_CODE + "=" + authzCode);
redirectUri += "&" + OAuth.OAUTH_STATE + "=“
+ request.getAttribute(OAuth.OAUTH_STATE);
resp.sendRedirect(redirectUri);
}
You Authorization
Server
Client
Application
Resource
Server
7. Here you are
6. I want to trade my
authorization code
for an access token
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
Token Endpoint (1)
@Path("/token")
public class TokenEndpoint {
...
@POST
public Response authorize(@Context HttpServletRequest request,
@HeaderParam(AUTHORIZATION) String authorizationHeader) {
// Do the required validations
validateClient(authorizationHeader);
OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
validateRedirectionURI(oauthRequest);
OAuthToken token = securityDataStore
.exchangeAuthorizationCodeForAccessToken(oauthRequest);
OAuthResponse oauthResponse = buildOAuthResponse(token);
return Response.status(oAuthResponse.getResponseStatus())
.entity(oAuthResponse.getBody()).build();
}
...
Token Endpoint (2)
...
private void validateClient(String authorizationHeader) {
Pattern headerPattern = Pattern.compile("s+");
String[] headerParts = headerPattern.split(authorizationHeader);
byte[] encoded = headerParts[1].getBytes();
String decoded = new String(Base64.decode(encoded),
Charset.forName("UTF-8"));
String[] clientParts = StringUtils.split(decoded, ":", 2);
String clientId = clientParts[0];
String clientSecret = clientParts[1];
if (!securityDataStore.isValidClient(clientId, clientSecret)) {
... // Create and throw an OAuthProblemException
}
}
...
You Authorization
Server
Client
Application
Resource
Server
7. Here you are
6. I want to trade my
authorization code
for an access token
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"
}
Token Endpoint (3)
...
private OAuthResponse buildOAuthResponse(OAuthToken token) {
return OAuthASResponse
.tokenResponse(HttpServletResponse.SC_OK)
.setAccessToken(token.getAccessToken())
.setTokenType(TokenType.BEARER)
.setExpiresIn(token.getExpiresIn())
.setRefreshToken(token.getRefreshToken())
.setScope(token.getScope())
.buildJSONMessage();
}
}
You Authorization
Server
Client
Application
Resource
Server
Give me some resources.
Here is my access token, btw.
…
GET /resource/1 HTTP/1.1
Host: example.com
Authorization: Bearer 2YotnFZFEjr1zCsicMWpAA
Resource Filter (1)
public class AuthorizationFilter implements ContainerRequestFilter {
@Context
private SecurityDataStore securityDataStore;
@Context
private HttpServletRequest httpServletRequest;
@Override
public ContainerRequest filter(ContainerRequest request) {
String accessToken = extractAccessToken();
validateAccessToken(accessToken);
return request;
}
...
Resource Filter (2)
...
private String extractAccessToken() {
OAuthAccessResourceRequest oauthRequest =
new OAuthAccessResourceRequest(httpServletRequest);
return oauthRequest.getAccessToken();
}
...
Resource Filter (3)
...
private void validateAccessToken(String accessToken) {
if (!securityDataStore.isValidAccessToken(accessToken)) {
throw new AuthorizationFailedException(
"Unknown or expired token!");
}
}
}
Summary
• OAuth 2.0 is ready for use
• Quite easy to use
• Don‘t go for least security
Uwe Friedrichsen
@ufried
uwe.friedrichsen@codecentric.de
http://www.slideshare.net/ufried/
http://blog.codecentric.de/author/ufr
OAuth 2.0

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

OAuth
OAuthOAuth
OAuth
 
Stateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWTStateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWT
 
OAuth2 and Spring Security
OAuth2 and Spring SecurityOAuth2 and Spring Security
OAuth2 and Spring Security
 
OAuth2 + API Security
OAuth2 + API SecurityOAuth2 + API Security
OAuth2 + API Security
 
SIngle Sign On with Keycloak
SIngle Sign On with KeycloakSIngle Sign On with Keycloak
SIngle Sign On with Keycloak
 
Secure your app with keycloak
Secure your app with keycloakSecure your app with keycloak
Secure your app with keycloak
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak
 
Implementing OAuth
Implementing OAuthImplementing OAuth
Implementing OAuth
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2
 
Spring Security
Spring SecuritySpring Security
Spring Security
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Introduction to JWT and How to integrate with Spring Security
Introduction to JWT and How to integrate with Spring SecurityIntroduction to JWT and How to integrate with Spring Security
Introduction to JWT and How to integrate with Spring Security
 
OpenID Connect: An Overview
OpenID Connect: An OverviewOpenID Connect: An Overview
OpenID Connect: An Overview
 
Spring security oauth2
Spring security oauth2Spring security oauth2
Spring security oauth2
 
Introducing Vault
Introducing VaultIntroducing Vault
Introducing Vault
 
Introduction to SAML 2.0
Introduction to SAML 2.0Introduction to SAML 2.0
Introduction to SAML 2.0
 
Keycloak SSO basics
Keycloak SSO basicsKeycloak SSO basics
Keycloak SSO basics
 
Getting Started with Spring Authorization Server
Getting Started with Spring Authorization ServerGetting Started with Spring Authorization Server
Getting Started with Spring Authorization Server
 
Draft: building secure applications with keycloak (oidc/jwt)
Draft: building secure applications with keycloak (oidc/jwt)Draft: building secure applications with keycloak (oidc/jwt)
Draft: building secure applications with keycloak (oidc/jwt)
 

Destacado

Fault tolerance made easy
Fault tolerance made easyFault tolerance made easy
Fault tolerance made easy
Uwe Friedrichsen
 

Destacado (20)

Securing RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID ConnectSecuring RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID Connect
 
Scalability patterns
Scalability patternsScalability patterns
Scalability patterns
 
Cloud fuer entscheider
Cloud fuer entscheiderCloud fuer entscheider
Cloud fuer entscheider
 
Cloud Compliance - Bestimmungen, Zertifizierungen und all das
Cloud Compliance - Bestimmungen, Zertifizierungen und all dasCloud Compliance - Bestimmungen, Zertifizierungen und all das
Cloud Compliance - Bestimmungen, Zertifizierungen und all das
 
Komplexität - Na und?
Komplexität - Na und?Komplexität - Na und?
Komplexität - Na und?
 
Emergent architecture
Emergent architectureEmergent architecture
Emergent architecture
 
Der Business Case für Architektur
Der Business Case für ArchitekturDer Business Case für Architektur
Der Business Case für Architektur
 
The agile Architect - Craftsmanship on a new Level
The agile Architect - Craftsmanship on a new LevelThe agile Architect - Craftsmanship on a new Level
The agile Architect - Craftsmanship on a new Level
 
Down with the_sandals
Down with the_sandalsDown with the_sandals
Down with the_sandals
 
No crash allowed - Fault tolerance patterns
No crash allowed - Fault tolerance patternsNo crash allowed - Fault tolerance patterns
No crash allowed - Fault tolerance patterns
 
Hochskalierbare Cloud-Architekturen
Hochskalierbare Cloud-ArchitekturenHochskalierbare Cloud-Architekturen
Hochskalierbare Cloud-Architekturen
 
Kommunikation und Qualität - Java Forum Nord 2016
Kommunikation und Qualität - Java Forum Nord 2016Kommunikation und Qualität - Java Forum Nord 2016
Kommunikation und Qualität - Java Forum Nord 2016
 
OAuth2: Uma abordagem para segurança de aplicações e APIs REST - Devcamp 2014
OAuth2: Uma abordagem para segurança de aplicações e APIs REST  - Devcamp 2014OAuth2: Uma abordagem para segurança de aplicações e APIs REST  - Devcamp 2014
OAuth2: Uma abordagem para segurança de aplicações e APIs REST - Devcamp 2014
 
Dr. Hectic and Mr. Hype - surviving the economic darwinism
Dr. Hectic and Mr. Hype - surviving the economic darwinismDr. Hectic and Mr. Hype - surviving the economic darwinism
Dr. Hectic and Mr. Hype - surviving the economic darwinism
 
RESTful Security
RESTful SecurityRESTful Security
RESTful Security
 
How to survive in a BASE world
How to survive in a BASE worldHow to survive in a BASE world
How to survive in a BASE world
 
OAuth2 Authentication
OAuth2 AuthenticationOAuth2 Authentication
OAuth2 Authentication
 
Deep Dive In To Kerberos
Deep Dive In To KerberosDeep Dive In To Kerberos
Deep Dive In To Kerberos
 
Protocolos de Segurança
Protocolos de SegurançaProtocolos de Segurança
Protocolos de Segurança
 
Fault tolerance made easy
Fault tolerance made easyFault tolerance made easy
Fault tolerance made easy
 

Similar a OAuth 2.0

Introduction to OAuth
Introduction to OAuthIntroduction to OAuth
Introduction to OAuth
Paul Osman
 
OAuth 2 at Webvisions
OAuth 2 at WebvisionsOAuth 2 at Webvisions
OAuth 2 at Webvisions
Aaron Parecki
 
Sfdc tournyc14 salesforceintegrationwithgoogledoubleclick__final_20141119
Sfdc tournyc14 salesforceintegrationwithgoogledoubleclick__final_20141119Sfdc tournyc14 salesforceintegrationwithgoogledoubleclick__final_20141119
Sfdc tournyc14 salesforceintegrationwithgoogledoubleclick__final_20141119
Ami Assayag
 

Similar a OAuth 2.0 (20)

OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe FriedrichsenOAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
 
iMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesiMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within Microservices
 
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
 
REST API Security: OAuth 2.0, JWTs, and More!
REST API Security: OAuth 2.0, JWTs, and More!REST API Security: OAuth 2.0, JWTs, and More!
REST API Security: OAuth 2.0, JWTs, and More!
 
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
 
OAuth 2.0 and Library
OAuth 2.0 and LibraryOAuth 2.0 and Library
OAuth 2.0 and Library
 
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
 
IdM and AC
IdM and ACIdM and AC
IdM and AC
 
Protecting your APIs with Doorkeeper and OAuth 2.0
Protecting your APIs with Doorkeeper and OAuth 2.0Protecting your APIs with Doorkeeper and OAuth 2.0
Protecting your APIs with Doorkeeper and OAuth 2.0
 
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
 
Accessing APIs using OAuth on the federated (WordPress) web
Accessing APIs using OAuth on the federated (WordPress) webAccessing APIs using OAuth on the federated (WordPress) web
Accessing APIs using OAuth on the federated (WordPress) web
 
OAuth and OEmbed
OAuth and OEmbedOAuth and OEmbed
OAuth and OEmbed
 
Some OAuth love
Some OAuth loveSome OAuth love
Some OAuth love
 
Introduction to OAuth
Introduction to OAuthIntroduction to OAuth
Introduction to OAuth
 
Demystifying REST
Demystifying RESTDemystifying REST
Demystifying REST
 
OAuth 2 at Webvisions
OAuth 2 at WebvisionsOAuth 2 at Webvisions
OAuth 2 at Webvisions
 
Sfdc tournyc14 salesforceintegrationwithgoogledoubleclick__final_20141119
Sfdc tournyc14 salesforceintegrationwithgoogledoubleclick__final_20141119Sfdc tournyc14 salesforceintegrationwithgoogledoubleclick__final_20141119
Sfdc tournyc14 salesforceintegrationwithgoogledoubleclick__final_20141119
 
Esquema de pasos de ejecución IdM
Esquema de pasos de ejecución IdMEsquema de pasos de ejecución IdM
Esquema de pasos de ejecución IdM
 
Demystifying OAuth2 for PHP
Demystifying OAuth2 for PHPDemystifying OAuth2 for PHP
Demystifying OAuth2 for PHP
 
Auth proxy pattern on Kubernetes
Auth proxy pattern on KubernetesAuth proxy pattern on Kubernetes
Auth proxy pattern on Kubernetes
 

Más de Uwe Friedrichsen

Timeless design in a cloud-native world
Timeless design in a cloud-native worldTimeless design in a cloud-native world
Timeless design in a cloud-native world
Uwe Friedrichsen
 
Deep learning - a primer
Deep learning - a primerDeep learning - a primer
Deep learning - a primer
Uwe Friedrichsen
 
Real-world consistency explained
Real-world consistency explainedReal-world consistency explained
Real-world consistency explained
Uwe Friedrichsen
 
The 7 quests of resilient software design
The 7 quests of resilient software designThe 7 quests of resilient software design
The 7 quests of resilient software design
Uwe Friedrichsen
 
Excavating the knowledge of our ancestors
Excavating the knowledge of our ancestorsExcavating the knowledge of our ancestors
Excavating the knowledge of our ancestors
Uwe Friedrichsen
 
The truth about "You build it, you run it!"
The truth about "You build it, you run it!"The truth about "You build it, you run it!"
The truth about "You build it, you run it!"
Uwe Friedrichsen
 
The promises and perils of microservices
The promises and perils of microservicesThe promises and perils of microservices
The promises and perils of microservices
Uwe Friedrichsen
 
Resilient Functional Service Design
Resilient Functional Service DesignResilient Functional Service Design
Resilient Functional Service Design
Uwe Friedrichsen
 
DevOps is not enough - Embedding DevOps in a broader context
DevOps is not enough - Embedding DevOps in a broader contextDevOps is not enough - Embedding DevOps in a broader context
DevOps is not enough - Embedding DevOps in a broader context
Uwe Friedrichsen
 

Más de Uwe Friedrichsen (20)

Timeless design in a cloud-native world
Timeless design in a cloud-native worldTimeless design in a cloud-native world
Timeless design in a cloud-native world
 
Deep learning - a primer
Deep learning - a primerDeep learning - a primer
Deep learning - a primer
 
Life after microservices
Life after microservicesLife after microservices
Life after microservices
 
The hitchhiker's guide for the confused developer
The hitchhiker's guide for the confused developerThe hitchhiker's guide for the confused developer
The hitchhiker's guide for the confused developer
 
Digitization solutions - A new breed of software
Digitization solutions - A new breed of softwareDigitization solutions - A new breed of software
Digitization solutions - A new breed of software
 
Real-world consistency explained
Real-world consistency explainedReal-world consistency explained
Real-world consistency explained
 
The 7 quests of resilient software design
The 7 quests of resilient software designThe 7 quests of resilient software design
The 7 quests of resilient software design
 
Excavating the knowledge of our ancestors
Excavating the knowledge of our ancestorsExcavating the knowledge of our ancestors
Excavating the knowledge of our ancestors
 
The truth about "You build it, you run it!"
The truth about "You build it, you run it!"The truth about "You build it, you run it!"
The truth about "You build it, you run it!"
 
The promises and perils of microservices
The promises and perils of microservicesThe promises and perils of microservices
The promises and perils of microservices
 
Resilient Functional Service Design
Resilient Functional Service DesignResilient Functional Service Design
Resilient Functional Service Design
 
Watch your communication
Watch your communicationWatch your communication
Watch your communication
 
Life, IT and everything
Life, IT and everythingLife, IT and everything
Life, IT and everything
 
Resilience reloaded - more resilience patterns
Resilience reloaded - more resilience patternsResilience reloaded - more resilience patterns
Resilience reloaded - more resilience patterns
 
DevOps is not enough - Embedding DevOps in a broader context
DevOps is not enough - Embedding DevOps in a broader contextDevOps is not enough - Embedding DevOps in a broader context
DevOps is not enough - Embedding DevOps in a broader context
 
Production-ready Software
Production-ready SoftwareProduction-ready Software
Production-ready Software
 
Towards complex adaptive architectures
Towards complex adaptive architecturesTowards complex adaptive architectures
Towards complex adaptive architectures
 
Conway's law revisited - Architectures for an effective IT
Conway's law revisited - Architectures for an effective ITConway's law revisited - Architectures for an effective IT
Conway's law revisited - Architectures for an effective IT
 
Microservices - stress-free and without increased heart attack risk
Microservices - stress-free and without increased heart attack riskMicroservices - stress-free and without increased heart attack risk
Microservices - stress-free and without increased heart attack risk
 
Patterns of resilience
Patterns of resiliencePatterns of resilience
Patterns of resilience
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

OAuth 2.0

  • 1. OAuth 2.0 A standard is coming of age Uwe Friedrichsen, codecentric AG, 2013
  • 3. <session> <no-code> <motivation /> <history /> <solution /> <extensions /> <criticism /> <tips /> </no-code> <code> <authzorization /> <token /> <resource /> </code> <wrap-up /> </session>
  • 4. { „session“ : { „no-code“ : [ „motivation“, „history“, „solution“, „extensions“, „criticism“, „tips“ ], „code“ : [ „authorization“, „token“, „resource“ ], „wrap-up“ : true }
  • 9. OAuth 1.0 • Started by Twitter in 2006 • 1st Draft Standard in 10/2007 • IETF RFC 5849 in 4/2010 • Widespread • Complex Client Security Handling • Limited Scope • Not extendable • Not „Enterprise-ready“
  • 10. OAuth 2.0 • Working Group started 4/2010 • 31 Draft Versions • Eran Hammer-Lahav left 7/2012 * • IETF RFC 6749 in 10/2012 * http://hueniverse.com/2012/07/ oauth-2-0-and-the-road-to-hell/
  • 13. Solution (Step 1) You Authorization Server Client Application Resource Server 1. I want an authorization code 4. Here is an authorization code for client XYZ 3. User: „Yes, it‘s okay“ 2.Client XYZ wants an authorization code 5. Here you are
  • 14. Solution (Step 2) You Authorization Server Client Application Resource Server 7. Here you are 6. I want to trade my authorization code for an access token
  • 15. Solution (Step 3) You Authorization Server Client Application Resource Server Give me some resources. Here is my access token, btw. …
  • 16. A few more Details • TLS/SSL • Endpoints • Client Types • Client Identifier • Client Authentication • Redirect URI • Access Token Scope • Refresh Token • Client State
  • 17. You Authorization Server Client Application Resource Server 1. I want an authorization code 4. Here is an authorization code for client XYZ 3. User: „Yes, it‘s okay“ 2.Client XYZ wants an authorization code 5. Here you areGET /authorize? response_type=code& client_id=s6BhdRkqt3& state=xyz& redirect_uri=https%3A%2F%2Fclient%2E example%2Ecom%2Fcb HTTP/1.1 Host: server.example.com
  • 18. You Authorization Server Client Application Resource Server 1. I want an authorization code 4. Here is an authorization code for client XYZ 3. User: „Yes, it‘s okay“ 2.Client XYZ wants an authorization code 5. Here you are HTTP/1.1 302 Found Location:  https://client.example.com/cb? code=SplxlOBeZQQYbYS6WxSbIA& state=xyz
  • 19. You Authorization Server Client Application Resource Server 7. Here you are 6. I want to trade my authorization code for an access token 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
  • 20. You Authorization Server Client Application Resource Server 7. Here you are 6. I want to trade my authorization code for an access token HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"bearer", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA" }
  • 21. You Authorization Server Client Application Resource Server Give me some resources. Here is my access token, btw. … GET /resource/1 HTTP/1.1 Host: example.com Authorization: Bearer 2YotnFZFEjr1zCsicMWpAA
  • 22. More flows & Extensions • Implicit Grant • Resource Owner Password Credentials Grant • Client Credentials Grant • Refresh Token Grant • Standard & custom Extensions • Standards based on OAuth 2.0
  • 23. Criticism • Too many compromises • No built-in security • Relies solely on SSL • Bearer Token • Self-encrypted token
  • 24. Tips • Turn MAY into MUST • Use HMAC Tokens • Use HMAC to sign Content • No self-encrypted token • Always check the SSL Certificate
  • 25. How does the code feel like? using Apache Amber 0.22
  • 26. You Authorization Server Client Application Resource Server 1. I want an authorization code 4. Here is an authorization code for client XYZ 3. User: „Yes, it‘s okay“ 2.Client XYZ wants an authorization code 5. Here you areGET /authorize? response_type=code& client_id=s6BhdRkqt3& state=xyz& redirect_uri=https%3A%2F%2Fclient%2E example%2Ecom%2Fcb HTTP/1.1 Host: server.example.com
  • 27. Authorization Endpoint (1) @Path("/authorize") public class AuthorizationEndpoint { @Context private SecurityDataStore securityDataStore; @GET @Consumes(OAuth.ContentType.URL_ENCODED) public Response authorize(@Context HttpServletRequest request) { // Do the required validations OAuthAuthzRequest oauthRequest = wrapAndValidate(request); validateRedirectionURI(oauthRequest); // Actual authentication not defined by OAuth 2.0 // Here a forward to a login page is used String loginURI = buildLoginURI(oauthRequest); return Response.status(HttpServletResponse.SC_FOUND) .location(new URI(loginUri)).build(); } ...
  • 28. Authorization Endpoint (2) ... private OAuthAuthzRequest wrapAndValidate(HttpServletRequest req) { // Implicitly validates the request locally return new OAuthAuthzRequest(req); } ...
  • 29. Authorization Endpoint (3) ... private void validateRedirectionURI(OAuthAuthzRequest oauthReq) { String redirectionURISent = oauthReq.getRedirectURI(); String redirectionURIStored = securityDataStore .getRedirectUriForClient(oauthReq.getClientId()); if (!redirectionURIStored .equalsIgnoreCase(redirectionURISent)) { OAuthProblemException oAuthProblem = OAuthProblemException .error(OAuthError.CodeResponse.ACCESS_DENIED, "Invalid Redirection URI"); oAuthProblem.setRedirectUri(redirectionURISent); throw oAuthProblem; } } ...
  • 30. Authorization Endpoint (4) ... private String buildLoginURI(OAuthAuthzRequest oauthRequest) { String loginURI = getBaseLoginURI(); // As an example loginURI += "&" + OAuth.OAUTH_RESPONSE_TYPE + "=“ + oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE); loginURI += "?" + OAuth.OAUTH_CLIENT_ID + "=“ + oauthRequest.getClientId(); loginURI += "&" + OAuth.OAUTH_REDIRECT_URI + "=“ + redirectUri; loginURI += "&" + OAuth.OAUTH_SCOPE + "=“ + getParam(OAuth.OAUTH_SCOPE); loginURI += "&" + OAuth.OAUTH_STATE + "=“ + getParam(OAuth.OAUTH_STATE); return loginURI; } }
  • 31. You Authorization Server Client Application Resource Server 1. I want an authorization code 4. Here is an authorization code for client XYZ 3. User: „Yes, it‘s okay“ 2.Client XYZ wants an authorization code 5. Here you are HTTP/1.1 302 Found Location:  https://client.example.com/cb? code=SplxlOBeZQQYbYS6WxSbIA& state=xyz
  • 32. Login page handler private void getAndSendAuthorizationCode(HttpServletRequest req, HttpServletResponse resp) { // Assuming login was successful and forwarded // parameters can be found in the request String userId = (String) request.getAttribute("userId"); String clientId = (String) request.getAttribute(OAuth.OAUTH_CLIENT_ID); // Create a new authorization code and store it in the database String authzCode = securityDataStore.getAuthorizationCode(userId, clientId); // Redirect back to client String redirectUri = (String) req.getAttribute(OAuth.OAUTH_REDIRECT_URI); redirectUri += "?" + OAuth.OAUTH_CODE + "=" + authzCode); redirectUri += "&" + OAuth.OAUTH_STATE + "=“ + request.getAttribute(OAuth.OAUTH_STATE); resp.sendRedirect(redirectUri); }
  • 33. You Authorization Server Client Application Resource Server 7. Here you are 6. I want to trade my authorization code for an access token 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
  • 34. Token Endpoint (1) @Path("/token") public class TokenEndpoint { ... @POST public Response authorize(@Context HttpServletRequest request, @HeaderParam(AUTHORIZATION) String authorizationHeader) { // Do the required validations validateClient(authorizationHeader); OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request); validateRedirectionURI(oauthRequest); OAuthToken token = securityDataStore .exchangeAuthorizationCodeForAccessToken(oauthRequest); OAuthResponse oauthResponse = buildOAuthResponse(token); return Response.status(oAuthResponse.getResponseStatus()) .entity(oAuthResponse.getBody()).build(); } ...
  • 35. Token Endpoint (2) ... private void validateClient(String authorizationHeader) { Pattern headerPattern = Pattern.compile("s+"); String[] headerParts = headerPattern.split(authorizationHeader); byte[] encoded = headerParts[1].getBytes(); String decoded = new String(Base64.decode(encoded), Charset.forName("UTF-8")); String[] clientParts = StringUtils.split(decoded, ":", 2); String clientId = clientParts[0]; String clientSecret = clientParts[1]; if (!securityDataStore.isValidClient(clientId, clientSecret)) { ... // Create and throw an OAuthProblemException } } ...
  • 36. You Authorization Server Client Application Resource Server 7. Here you are 6. I want to trade my authorization code for an access token HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"bearer", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA" }
  • 37. Token Endpoint (3) ... private OAuthResponse buildOAuthResponse(OAuthToken token) { return OAuthASResponse .tokenResponse(HttpServletResponse.SC_OK) .setAccessToken(token.getAccessToken()) .setTokenType(TokenType.BEARER) .setExpiresIn(token.getExpiresIn()) .setRefreshToken(token.getRefreshToken()) .setScope(token.getScope()) .buildJSONMessage(); } }
  • 38. You Authorization Server Client Application Resource Server Give me some resources. Here is my access token, btw. … GET /resource/1 HTTP/1.1 Host: example.com Authorization: Bearer 2YotnFZFEjr1zCsicMWpAA
  • 39. Resource Filter (1) public class AuthorizationFilter implements ContainerRequestFilter { @Context private SecurityDataStore securityDataStore; @Context private HttpServletRequest httpServletRequest; @Override public ContainerRequest filter(ContainerRequest request) { String accessToken = extractAccessToken(); validateAccessToken(accessToken); return request; } ...
  • 40. Resource Filter (2) ... private String extractAccessToken() { OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(httpServletRequest); return oauthRequest.getAccessToken(); } ...
  • 41. Resource Filter (3) ... private void validateAccessToken(String accessToken) { if (!securityDataStore.isValidAccessToken(accessToken)) { throw new AuthorizationFailedException( "Unknown or expired token!"); } } }
  • 42. Summary • OAuth 2.0 is ready for use • Quite easy to use • Don‘t go for least security