SlideShare a Scribd company logo
1 of 57
Download to read offline
Implementing OAuth
About Me

 • Lorna Jane Mitchell

 • PHP Consultant/Developer

 • Occasional writer/speaker/trainer

 • Twitter: @lornajane

 • Website: http://lornajane.net




                                       2
About Me

 • Lorna Jane Mitchell

 • PHP Consultant/Developer

 • Occasional writer/speaker/trainer

 • Twitter: @lornajane

 • Website: http://lornajane.net

 • I am excited about OAuth :)




                                       2
About This Talk

  • Covering OAuth1 and OAuth2

  • OAuth1 needs more explanation

  • OAuth v1.0a is current stable

  • OAuth2 in use by Google, Facebook and others

  • Ask questions at any time




                                                   3
About OAuth

 • Provider has User data

 • User wants data to be available to 3rd party

 • User tells Provider to grant access to Consumer

 • Access may be limited

 • User can revoke at any time

 • Provider can distinguish between User and Consumer




                                                        4
OAuth Terminology

Provider   The app with the interesting data
Consumer   The app that wants the data
User       Who the data belongs to
Token      Random string
Secret     Another random string, linked to a token
Verifier    Another random string




                                                      5
OAuth HowTo
OAuth Dance




              7
Dance Steps

 • Step 0: Register as a consumer

 • Step 1: Get a request token

 • Step 2: Send the user to authenticate

 • Step 3: Swap their verification for an access token

 • Step 4: Consume data




                                                        8
Step 0: Register

  • Akin to registering for an API key

  • Introduce the Provider and Consumer




                                          9
Step 1: Get A Request Token

Consumer asks for a request token from the Provider’s request token
endpoint, specifying the callback URL




We give the token to the user and send them to log in



                                                                      10
Step 2: User Grants Access

We send the user to the Provider, with the request token, to log in




                                                                      11
Step 2: User Grants Access

We send the user to the Provider, with the request token, to log in




 The Provider returns them to us, at the callback URL, with a verifier code

                                                                             11
Devices Where Callback Won’t Work

It is hard to forward a user from a browser back to an app

   • Instead we use "oob" as the callback parameter

   • Provider displays verifier on screen

   • User types code into app manually




                                                             12
Step 3: Get an Access Token

Consumer makes a request to Provider’s access token endpoint with:

  • Consumer key

  • Request token

  • Verifier




                                                                     13
Step 3: Get an Access Token

Consumer makes a request to Provider’s access token endpoint with:

  • Consumer key

  • Request token

  • Verifier




                                                                     13
OAuth Theory
Transmitting OAuth Parameters

We have three choices:

  • As query parameters on the URL

  • Use an Authorization Header

  • Include the data as POST data




                                     15
OAuth Request Token Fields

Asking for a request token looks like this:
https://api.login.yahoo.com/oauth/v2/
  get_request_token?oauth_nonce=ce2130523f788f313f76314ed3965ea6
  &oauth_timestamp=1202956957
  &oauth_consumer_key=123456891011121314151617181920
  &oauth_signature_method=plaintext
  &oauth_signature=abcdef
  &oauth_version=1.0
  &oauth_callback="http://yoursite.com/callback"
http://developer.yahoo.com/oauth/guide/oauth-requesttoken.html


We supplied the oauth_consumer_key and oauth_callback but what are these
other fields?




                                                                           16
OAuth Request Token Fields

 • signature method: How the request is signed. Typically
   plaintext or HMAC-SHA1




                                                            17
OAuth Request Token Fields

 • signature method: How the request is signed. Typically
   plaintext or HMAC-SHA1

 • nonce: Cryptographic term meaning "Number Used Once". We
   think of a number, then throw it away




                                                              17
OAuth Request Token Fields

 • signature method: How the request is signed. Typically
   plaintext or HMAC-SHA1

 • nonce: Cryptographic term meaning "Number Used Once". We
   think of a number, then throw it away

 • timestamp: Number of seconds since the epoch




                                                              17
OAuth Request Token Fields

 • signature method: How the request is signed. Typically
   plaintext or HMAC-SHA1

 • nonce: Cryptographic term meaning "Number Used Once". We
   think of a number, then throw it away

 • timestamp: Number of seconds since the epoch

 • version: 1.0 in this instance (more on OAuth2 later)




                                                              17
OAuth Request Token Fields

 • signature method: How the request is signed. Typically
   plaintext or HMAC-SHA1

 • nonce: Cryptographic term meaning "Number Used Once". We
   think of a number, then throw it away

 • timestamp: Number of seconds since the epoch

 • version: 1.0 in this instance (more on OAuth2 later)

 • signature:




                                                              17
OAuth Request Token Fields

  • signature method: How the request is signed. Typically
    plaintext or HMAC-SHA1

  • nonce: Cryptographic term meaning "Number Used Once". We
    think of a number, then throw it away

  • timestamp: Number of seconds since the epoch

  • version: 1.0 in this instance (more on OAuth2 later)

  • signature:

If you care, read this: http://bit.ly/gTJGPZ




                                                               17
Practical Examples
OAuth Tools

PHP tools for OAuth:

  • Pecl OAuth

       • http://uk2.php.net/manual/en/class.oauth.php
       • Talk examples use this

  • Zend OAuth

       • http://framework.zend.com/manual/en/zend.oauth.html




                                                               19
Providing and Consuming OAuth

  • Consuming:

      • relatively easy
      • used for authenticating against e.g. twitter

  • Providing:

      • more overhead than consuming
      • great way to give access to applications
      • needs multiple pages and endpoints as well as the API itself


Provider code with dark background

Consumer code with a blue background



                                                                       20
Provider: Auxiliary Web Pages

There are some additional functions to provide as a provider:

   • Consumer signup page, like an API key

   • User authorisation step to allow/deny access for this consumer

   • Rights management page so users can control/revoke access later




                                                                       21
Provider: Step 0, Consumer Keys

This is straightforward

   • Generate a key and a secret, store them

   • Return them to the consumer to use

   • Can use OAuth libraries, or not

$hash = sha1(mt_rand()); // there are many ways to do this
$consumer_key = substr($hash,0,30);
$consumer_secret = substr($hash,30,10);




                                                             22
Provider: Handling OAuth Requests With Pecl

For every incoming request, for tokens and in normal operation, we’ll have
code like this:
$this->provider = new OAuthProvider();

// set names of functions to be called by the extension
$this->provider->consumerHandler(array($this,'lookupConsumer'));
$this->provider->timestampNonceHandler(
    array($this,'timestampNonceChecker'));
$this->provider->tokenHandler(array($this,'tokenHandler'));

// no access token needed for this URL only
$this->provider->setRequestTokenPath('/v2/oauth/request_token');

$this->provider->checkOAuthRequest();




                                                                             23
Step 1




                consumer key, callback

  Consumer                                   Provider
             request token, request secret




                                                        24
Consumer: Step 1, Request Token

$config = array();

$config['request_uri'] = 'http://api.local/v2/oauth/request_token';
$config['consumer_key'] = 'akey';
$config['consumer_secret'] = 'asecret';

$oauth = new OAuth($config['consumer_key'],
                    $config['consumer_secret']
                    );

$oauth->setAuthType(OAUTH_AUTH_TYPE_URI);
$req = $oauth->getRequestToken($config['request_uri'], "oob");




                                                                      25
Provider: Step 1, Request Token Request

  • Check oauth signature and consumer key

  • Generate a request token and store it

  • Return the request token




                                             26
Provider: Step 1, Generate Request Token

Retrieve the callback, and make the token and secret:
// remember we're in URI mode
parse_str($_SERVER['QUERY_STRING'], &$parameters);
$callback = $parameters['oauth_callback'];
$request_token = bin2hex($provider->generateToken(4));
$request_token_secret = bin2hex($provider->generateToken(12));




We then simply echo the resulting variables in query format, e.g.
echo 'login_url = http://api.joindin.local/user/oauth_allow?' .
     'request_token = ' . $request_token .
     '&request_token_secret = ' . $request_token_secret .
     '&oauth_callback_confirmed = true';




                                                                    27
Storing Request Tokens

Storage is simple, again, you know all this
+----------------------+--------------+
| Field                | Type         |
+----------------------+--------------+
| id                   | int(11)      |
| consumer_key         | varchar(30) |
| request_token        | varchar(8)   |
| request_token_secret | varchar(32) |
| callback             | varchar(400) |
| verification         | varchar(20) |
| authorised_user_id   | int(11)      |
| created_date         | timestamp    |
+----------------------+--------------+




                                              28
Step 2, User Grants Access

User grants access




                             29
Provider: Step 2, Granting/Denying Access

User grants access:

  • store user id against request token

  • generate a verifier code and store that too

User denies access:

  • delete request token




                                                 30
Step 2, For Devices

Instead of forwarding the user, give them a code to use




                                                          31
Step 3




                 consumer key,
              request token, verifier
   Consumer                            Provider
                  access token




                                                  32
Consumer: Step 3, Request an Access Token

$oauth = new OAuth($config['consumer_key'],
                    $config['consumer_secret']);

// request token, request token secret and verification all set
// by earlier steps, and loaded into $config
try{
     $oauth->setToken(
         $config['request_token'],
         $config['request_token_secret']);
     $access = $oauth->getAccessToken($config['access_uri'], null,
         $config['verification']);
} catch (OAuthException $e) {
     echo $e->getMessage();
}




                                                                     33
Provider: Step 3, Generate Access Token

Generate and store access token and secret, then return:
echo "oauth_token=" . $tokens['oauth_token']
    . '&oauth_token_secret=' . $tokens['oauth_token_secret'];




                                                                34
Storing Access Tokens

+---------------------+-------------+
| Field               | Type        |
+---------------------+-------------+
| id                  | int(11)     |
| consumer_key        | varchar(30) |
| access_token        | varchar(16) |
| access_token_secret | varchar(32) |
| user_id             | int(11)     |
| created_date        | timestamp   |
| last_used_date      | datetime    |
+---------------------+-------------+




                                        35
Step 4




                   consumer key,
              access token, API request
   Consumer                               Provider
                    API response




                                                     36
Consumer: Step 4, Subsequent Requests

$oauth = new OAuth($config['consumer_key'],
    $config['consumer_secret']);

// from the getAccessToken call
$oauth->setToken($oauth_token, $oauth_token_secret);
$result = $oauth->fetch("http://api.local/usual/call/here");
if($result) {
    $response = $oauth->getLastResponse();
}




                                                               37
Debugging

 • For pecl_oauth:

     • Use OAuth::enableDebug() to turn on verbose debugging
     • The debug information is available in OAuth::debugInfo
     • For the provider, use OAuthProvider::reportProblem()

 • Wireshark or Charles Proxy

     • http://www.wireshark.org/
     • http://www.charlesproxy.com/




                                                                38
Other OAuth Types
3-legged OAuth

So far we have discussed 3-legged OAuth

  • Three parties are involved

       • Consumer
       • Provider
       • User




                                          40
2-legged OAuth

2-legged OAuth is also an option

  • Only two parties involved now

       • Provider
       • User/Client

  • Step 0: User signs up for credentials similar to consumer key/secret

  • Step 4: User makes request using

       • their key and secret
       • empty token details




                                                                           41
OAuth 2

 • Same principles and intention

 • Spec still at draft stage officially

 • Used by Google, Facebook and others

 • Aims to be less complicated than OAuth 1

 • Intended to be more scalable - provider split into resources and auth
   servers

 • No signing, SSL recommended instead




                                                                           42
OAuth2 Outline

    +--------+                               +---------------+
    |        |--(A)- Authorization Request ->|   Resource    |
    |        |                               |     Owner     |
    |        |<-(B)-- Authorization Grant ---|               |
    |        |                               +---------------+
    |        |
    |        |        Authorization Grant & +---------------+
    |        |--(C)--- Client Credentials -->| Authorization |
    | Client |                               |     Server    |
    |        |<-(D)----- Access Token -------|               |
    |        |                               +---------------+
    |        |
    |        |                               +---------------+
    |        |--(E)----- Access Token ------>|    Resource   |
    |        |                               |     Server    |
    |        |<-(F)--- Protected Resource ---|               |
    +--------+                               +---------------+

Diagram from OAuth2 spec
http://tools.ietf.org/html/draft-ietf-oauth-v2-15

                                                                 43
Authorization Grant

Can take many forms

  • Username and password

      • used once to obtain an access token
      • or just used as access token

  • Client credentials

      • client has prearranged access to the resource

  • Implicit

      • an access token provided some other way

  • Authorization Code

      • similar to OAuth 1, send user to talk to Auth Server and get
        verification codes
                                                                       44
Access Tokens and Refresh Tokens

Refresh Tokens are an optional addition to OAuth 2

  • Auth Server can return a refresh token with an access token

  • Refresh token has longer validity

  • Can be exchanged for an access token when combined with other
    details

  • Compare with re-entering your password at intervals




                                                                    45
The State of OAuth

  • OAuth 1

     • already in use
     • a faff!

  • OAuth 2

     • still being finalised
     • different approach to same problem




                                            46
Questions?
Resources

 • PHP Manual: http://uk2.php.net/manual/en/book.oauth.php

 • Rasmus’ OAuth Provider Example: http://bit.ly/i76Tzx

 • Yahoo Developer Network Documentation:
   http://developer.yahoo.com/oauth/guide/

 • Eran Hammer-Lahav’s blog: http://hueniverse.com

 • 2-legged OAuth post: http://bit.ly/ejQRoK

 • OAuth 2 Draft Spec:
   http://tools.ietf.org/html/draft-ietf-oauth-v2-15




                                                             48
Thanks!




             Thanks!
          http://joind.in/3243/




               @lornajane

          http://lornajane.net/




                                  49

More Related Content

What's hot

RPで受け入れる認証器を選択する ~Idance lesson 2~
RPで受け入れる認証器を選択する ~Idance lesson 2~RPで受け入れる認証器を選択する ~Idance lesson 2~
RPで受け入れる認証器を選択する ~Idance lesson 2~5 6
 
Modern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensModern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensJonathan LeBlanc
 
OAuth & OpenID Connect Deep Dive
OAuth & OpenID Connect Deep DiveOAuth & OpenID Connect Deep Dive
OAuth & OpenID Connect Deep DiveNordic APIs
 
OpenID Connect Client Initiated Backchannel Authentication Flow (CIBA)のご紹介 ~ ...
OpenID Connect Client Initiated Backchannel Authentication Flow (CIBA)のご紹介 ~ ...OpenID Connect Client Initiated Backchannel Authentication Flow (CIBA)のご紹介 ~ ...
OpenID Connect Client Initiated Backchannel Authentication Flow (CIBA)のご紹介 ~ ...OpenID Foundation Japan
 
Googleログインから学ぶ OAuth
Googleログインから学ぶ OAuthGoogleログインから学ぶ OAuth
Googleログインから学ぶ OAuthKazuma Kimura
 
MicrometerとPrometheusによる LINEファミリーアプリのモニタリング
MicrometerとPrometheusによる LINEファミリーアプリのモニタリングMicrometerとPrometheusによる LINEファミリーアプリのモニタリング
MicrometerとPrometheusによる LINEファミリーアプリのモニタリングLINE Corporation
 
Lekts presentation6
Lekts presentation6Lekts presentation6
Lekts presentation6ganzorigb
 
Burp suite を使って iPhone アプリを診断した時に困ったことと、解決方法
Burp suite を使って iPhone アプリを診断した時に困ったことと、解決方法Burp suite を使って iPhone アプリを診断した時に困ったことと、解決方法
Burp suite を使って iPhone アプリを診断した時に困ったことと、解決方法tobaru_yuta
 
今更聞けない電子認証入門 -OAuth 2.0/OIDCからFIDOまで- <改定2版>
今更聞けない電子認証入門 -OAuth 2.0/OIDCからFIDOまで- <改定2版>今更聞けない電子認証入門 -OAuth 2.0/OIDCからFIDOまで- <改定2版>
今更聞けない電子認証入門 -OAuth 2.0/OIDCからFIDOまで- <改定2版>Naoto Miyachi
 
Кибэр аюулгүй байдал.
Кибэр аюулгүй байдал.Кибэр аюулгүй байдал.
Кибэр аюулгүй байдал.Bilguun Bicktivism
 
РЕСТОРАНЫ ХООЛ ЗАХИАЛГЫН СИСТЕМ
РЕСТОРАНЫ ХООЛ ЗАХИАЛГЫН СИСТЕМ РЕСТОРАНЫ ХООЛ ЗАХИАЛГЫН СИСТЕМ
РЕСТОРАНЫ ХООЛ ЗАХИАЛГЫН СИСТЕМ hulan lara
 
認証サービスへのWebAuthnの導入
認証サービスへのWebAuthnの導入認証サービスへのWebAuthnの導入
認証サービスへのWebAuthnの導入TakashiTsukamoto4
 
Understanding JWT Exploitation
Understanding JWT ExploitationUnderstanding JWT Exploitation
Understanding JWT ExploitationAkshaeyBhosale
 

What's hot (20)

RPで受け入れる認証器を選択する ~Idance lesson 2~
RPで受け入れる認証器を選択する ~Idance lesson 2~RPで受け入れる認証器を選択する ~Idance lesson 2~
RPで受け入れる認証器を選択する ~Idance lesson 2~
 
Системийн шинжилгээ, зохиомж
Системийн шинжилгээ, зохиомжСистемийн шинжилгээ, зохиомж
Системийн шинжилгээ, зохиомж
 
Modern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensModern API Security with JSON Web Tokens
Modern API Security with JSON Web Tokens
 
It101 lect9
It101 lect9It101 lect9
It101 lect9
 
Json web token
Json web tokenJson web token
Json web token
 
OAuth & OpenID Connect Deep Dive
OAuth & OpenID Connect Deep DiveOAuth & OpenID Connect Deep Dive
OAuth & OpenID Connect Deep Dive
 
JSON WEB TOKEN
JSON WEB TOKENJSON WEB TOKEN
JSON WEB TOKEN
 
OpenID Connect Client Initiated Backchannel Authentication Flow (CIBA)のご紹介 ~ ...
OpenID Connect Client Initiated Backchannel Authentication Flow (CIBA)のご紹介 ~ ...OpenID Connect Client Initiated Backchannel Authentication Flow (CIBA)のご紹介 ~ ...
OpenID Connect Client Initiated Backchannel Authentication Flow (CIBA)のご紹介 ~ ...
 
Googleログインから学ぶ OAuth
Googleログインから学ぶ OAuthGoogleログインから学ぶ OAuth
Googleログインから学ぶ OAuth
 
MicrometerとPrometheusによる LINEファミリーアプリのモニタリング
MicrometerとPrometheusによる LINEファミリーアプリのモニタリングMicrometerとPrometheusによる LINEファミリーアプリのモニタリング
MicrometerとPrometheusによる LINEファミリーアプリのモニタリング
 
Lekts presentation6
Lekts presentation6Lekts presentation6
Lekts presentation6
 
Lecture8 9
Lecture8 9Lecture8 9
Lecture8 9
 
Burp suite を使って iPhone アプリを診断した時に困ったことと、解決方法
Burp suite を使って iPhone アプリを診断した時に困ったことと、解決方法Burp suite を使って iPhone アプリを診断した時に困ったことと、解決方法
Burp suite を使って iPhone アプリを診断した時に困ったことと、解決方法
 
今更聞けない電子認証入門 -OAuth 2.0/OIDCからFIDOまで- <改定2版>
今更聞けない電子認証入門 -OAuth 2.0/OIDCからFIDOまで- <改定2版>今更聞けない電子認証入門 -OAuth 2.0/OIDCからFIDOまで- <改定2版>
今更聞けない電子認証入門 -OAuth 2.0/OIDCからFIDOまで- <改定2版>
 
OpenID Connect Explained
OpenID Connect ExplainedOpenID Connect Explained
OpenID Connect Explained
 
Кибэр аюулгүй байдал.
Кибэр аюулгүй байдал.Кибэр аюулгүй байдал.
Кибэр аюулгүй байдал.
 
РЕСТОРАНЫ ХООЛ ЗАХИАЛГЫН СИСТЕМ
РЕСТОРАНЫ ХООЛ ЗАХИАЛГЫН СИСТЕМ РЕСТОРАНЫ ХООЛ ЗАХИАЛГЫН СИСТЕМ
РЕСТОРАНЫ ХООЛ ЗАХИАЛГЫН СИСТЕМ
 
OAuth2 + API Security
OAuth2 + API SecurityOAuth2 + API Security
OAuth2 + API Security
 
認証サービスへのWebAuthnの導入
認証サービスへのWebAuthnの導入認証サービスへのWebAuthnの導入
認証サービスへのWebAuthnの導入
 
Understanding JWT Exploitation
Understanding JWT ExploitationUnderstanding JWT Exploitation
Understanding JWT Exploitation
 

Viewers also liked

Using OAuth with PHP
Using OAuth with PHPUsing OAuth with PHP
Using OAuth with PHPDavid Ingram
 
An Introduction to OAuth 2
An Introduction to OAuth 2An Introduction to OAuth 2
An Introduction to OAuth 2Aaron Parecki
 
Annotating with Annotations - ForumPHP 2012
Annotating with Annotations - ForumPHP 2012Annotating with Annotations - ForumPHP 2012
Annotating with Annotations - ForumPHP 2012Rafael Dohms
 
Twitter API & OAuth 101 TVUG October 2009
Twitter API & OAuth 101 TVUG October 2009Twitter API & OAuth 101 TVUG October 2009
Twitter API & OAuth 101 TVUG October 2009Andrew Badera
 
OpenStack: leggero, aperto e basato sul web.
OpenStack: leggero, aperto e basato sul web.OpenStack: leggero, aperto e basato sul web.
OpenStack: leggero, aperto e basato sul web.Lorenzo Cassulo
 
Distributed Identities with OpenID
Distributed Identities with OpenIDDistributed Identities with OpenID
Distributed Identities with OpenIDBastian Hofmann
 
PHP, OAuth, Web Services and YQL
PHP, OAuth, Web Services and YQLPHP, OAuth, Web Services and YQL
PHP, OAuth, Web Services and YQLkulor
 
API Security and OAuth for the Enterprise
API Security and OAuth for the EnterpriseAPI Security and OAuth for the Enterprise
API Security and OAuth for the EnterpriseCA API Management
 
OpenID vs OAuth - Identity on the Web
OpenID vs OAuth - Identity on the WebOpenID vs OAuth - Identity on the Web
OpenID vs OAuth - Identity on the WebRichard Metzler
 
Secure and Govern Integration between the Enterprise & the Cloud
Secure and Govern Integration between the Enterprise & the CloudSecure and Govern Integration between the Enterprise & the Cloud
Secure and Govern Integration between the Enterprise & the CloudCA API Management
 
Securing your Web API with OAuth
Securing your Web API with OAuthSecuring your Web API with OAuth
Securing your Web API with OAuthMohan Krishnan
 
Interface Drupal with desktop or webapp via OAuth & REST
Interface Drupal with desktop or webapp via OAuth & RESTInterface Drupal with desktop or webapp via OAuth & REST
Interface Drupal with desktop or webapp via OAuth & RESTNicolas Froment
 

Viewers also liked (17)

Using OAuth with PHP
Using OAuth with PHPUsing OAuth with PHP
Using OAuth with PHP
 
An Introduction to OAuth 2
An Introduction to OAuth 2An Introduction to OAuth 2
An Introduction to OAuth 2
 
Annotating with Annotations - ForumPHP 2012
Annotating with Annotations - ForumPHP 2012Annotating with Annotations - ForumPHP 2012
Annotating with Annotations - ForumPHP 2012
 
Twitter API & OAuth 101 TVUG October 2009
Twitter API & OAuth 101 TVUG October 2009Twitter API & OAuth 101 TVUG October 2009
Twitter API & OAuth 101 TVUG October 2009
 
OpenStack: leggero, aperto e basato sul web.
OpenStack: leggero, aperto e basato sul web.OpenStack: leggero, aperto e basato sul web.
OpenStack: leggero, aperto e basato sul web.
 
Distributed Identities with OpenID
Distributed Identities with OpenIDDistributed Identities with OpenID
Distributed Identities with OpenID
 
PHP, OAuth, Web Services and YQL
PHP, OAuth, Web Services and YQLPHP, OAuth, Web Services and YQL
PHP, OAuth, Web Services and YQL
 
Data Driven Security
Data Driven SecurityData Driven Security
Data Driven Security
 
Single Sign on e OpenID
Single Sign on e OpenIDSingle Sign on e OpenID
Single Sign on e OpenID
 
API Security and OAuth for the Enterprise
API Security and OAuth for the EnterpriseAPI Security and OAuth for the Enterprise
API Security and OAuth for the Enterprise
 
Oauth
OauthOauth
Oauth
 
OAuth: The API Gatekeeper
OAuth: The API GatekeeperOAuth: The API Gatekeeper
OAuth: The API Gatekeeper
 
OpenID vs OAuth - Identity on the Web
OpenID vs OAuth - Identity on the WebOpenID vs OAuth - Identity on the Web
OpenID vs OAuth - Identity on the Web
 
Secure and Govern Integration between the Enterprise & the Cloud
Secure and Govern Integration between the Enterprise & the CloudSecure and Govern Integration between the Enterprise & the Cloud
Secure and Govern Integration between the Enterprise & the Cloud
 
Securing your Web API with OAuth
Securing your Web API with OAuthSecuring your Web API with OAuth
Securing your Web API with OAuth
 
OpenID and OAuth
OpenID and OAuthOpenID and OAuth
OpenID and OAuth
 
Interface Drupal with desktop or webapp via OAuth & REST
Interface Drupal with desktop or webapp via OAuth & RESTInterface Drupal with desktop or webapp via OAuth & REST
Interface Drupal with desktop or webapp via OAuth & REST
 

Similar to Implementing OAuth with PHP

LinkedIn OAuth: Zero To Hero
LinkedIn OAuth: Zero To HeroLinkedIn OAuth: Zero To Hero
LinkedIn OAuth: Zero To HeroTaylor Singletary
 
oauth-for-credentials-security-in-rest-api-access
oauth-for-credentials-security-in-rest-api-accessoauth-for-credentials-security-in-rest-api-access
oauth-for-credentials-security-in-rest-api-accessidsecconf
 
OAuth [noddyCha]
OAuth [noddyCha]OAuth [noddyCha]
OAuth [noddyCha]noddycha
 
OAuth 2.0 Misconceptions
OAuth 2.0 MisconceptionsOAuth 2.0 Misconceptions
OAuth 2.0 MisconceptionsCory Forsyth
 
Spring4 security oauth2
Spring4 security oauth2Spring4 security oauth2
Spring4 security oauth2axykim00
 
Spring4 security oauth2
Spring4 security oauth2Spring4 security oauth2
Spring4 security oauth2Sang Shin
 
Spring security oauth2
Spring security oauth2Spring security oauth2
Spring security oauth2axykim00
 
Mobile Authentication - Onboarding, best practices & anti-patterns
Mobile Authentication - Onboarding, best practices & anti-patternsMobile Authentication - Onboarding, best practices & anti-patterns
Mobile Authentication - Onboarding, best practices & anti-patternsPieter Ennes
 
Secure your app with keycloak
Secure your app with keycloakSecure your app with keycloak
Secure your app with keycloakGuy Marom
 
Securing APIs with OAuth 2.0
Securing APIs with OAuth 2.0Securing APIs with OAuth 2.0
Securing APIs with OAuth 2.0Kai Hofstetter
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2Sanjoy Kumar Roy
 
OAuth2 Best Practices in Native Apps
OAuth2 Best Practices in Native AppsOAuth2 Best Practices in Native Apps
OAuth2 Best Practices in Native AppsJeff Fontas
 
Authorization with oAuth
Authorization with oAuthAuthorization with oAuth
Authorization with oAuthVivastream
 
O auth how_to
O auth how_toO auth how_to
O auth how_tovivaqa
 
Oauth 2.0 security
Oauth 2.0 securityOauth 2.0 security
Oauth 2.0 securityvinoth kumar
 
Intro to OAuth2 and OpenID Connect
Intro to OAuth2 and OpenID ConnectIntro to OAuth2 and OpenID Connect
Intro to OAuth2 and OpenID ConnectLiamWadman
 
Ember Authentication and Authorization with Torii
Ember Authentication and Authorization with ToriiEmber Authentication and Authorization with Torii
Ember Authentication and Authorization with ToriiCory Forsyth
 
OAuth and OEmbed
OAuth and OEmbedOAuth and OEmbed
OAuth and OEmbedleahculver
 

Similar to Implementing OAuth with PHP (20)

LinkedIn OAuth: Zero To Hero
LinkedIn OAuth: Zero To HeroLinkedIn OAuth: Zero To Hero
LinkedIn OAuth: Zero To Hero
 
oauth-for-credentials-security-in-rest-api-access
oauth-for-credentials-security-in-rest-api-accessoauth-for-credentials-security-in-rest-api-access
oauth-for-credentials-security-in-rest-api-access
 
OAuth: Trust Issues
OAuth: Trust IssuesOAuth: Trust Issues
OAuth: Trust Issues
 
OAuth [noddyCha]
OAuth [noddyCha]OAuth [noddyCha]
OAuth [noddyCha]
 
Api security
Api security Api security
Api security
 
OAuth 2.0 Misconceptions
OAuth 2.0 MisconceptionsOAuth 2.0 Misconceptions
OAuth 2.0 Misconceptions
 
Spring4 security oauth2
Spring4 security oauth2Spring4 security oauth2
Spring4 security oauth2
 
Spring4 security oauth2
Spring4 security oauth2Spring4 security oauth2
Spring4 security oauth2
 
Spring security oauth2
Spring security oauth2Spring security oauth2
Spring security oauth2
 
Mobile Authentication - Onboarding, best practices & anti-patterns
Mobile Authentication - Onboarding, best practices & anti-patternsMobile Authentication - Onboarding, best practices & anti-patterns
Mobile Authentication - Onboarding, best practices & anti-patterns
 
Secure your app with keycloak
Secure your app with keycloakSecure your app with keycloak
Secure your app with keycloak
 
Securing APIs with OAuth 2.0
Securing APIs with OAuth 2.0Securing APIs with OAuth 2.0
Securing APIs with OAuth 2.0
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2
 
OAuth2 Best Practices in Native Apps
OAuth2 Best Practices in Native AppsOAuth2 Best Practices in Native Apps
OAuth2 Best Practices in Native Apps
 
Authorization with oAuth
Authorization with oAuthAuthorization with oAuth
Authorization with oAuth
 
O auth how_to
O auth how_toO auth how_to
O auth how_to
 
Oauth 2.0 security
Oauth 2.0 securityOauth 2.0 security
Oauth 2.0 security
 
Intro to OAuth2 and OpenID Connect
Intro to OAuth2 and OpenID ConnectIntro to OAuth2 and OpenID Connect
Intro to OAuth2 and OpenID Connect
 
Ember Authentication and Authorization with Torii
Ember Authentication and Authorization with ToriiEmber Authentication and Authorization with Torii
Ember Authentication and Authorization with Torii
 
OAuth and OEmbed
OAuth and OEmbedOAuth and OEmbed
OAuth and OEmbed
 

More from Lorna Mitchell

Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API DesignLorna Mitchell
 
Git, GitHub and Open Source
Git, GitHub and Open SourceGit, GitHub and Open Source
Git, GitHub and Open SourceLorna Mitchell
 
Business 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyBusiness 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyLorna Mitchell
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knewLorna Mitchell
 
Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Lorna Mitchell
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP StackLorna Mitchell
 
Understanding Distributed Source Control
Understanding Distributed Source ControlUnderstanding Distributed Source Control
Understanding Distributed Source ControlLorna Mitchell
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service DesignLorna Mitchell
 
Coaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishCoaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishLorna Mitchell
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Could You Telecommute?
Could You Telecommute?Could You Telecommute?
Could You Telecommute?Lorna Mitchell
 
Running a Project with Github
Running a Project with GithubRunning a Project with Github
Running a Project with GithubLorna Mitchell
 

More from Lorna Mitchell (20)

Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API Design
 
Git, GitHub and Open Source
Git, GitHub and Open SourceGit, GitHub and Open Source
Git, GitHub and Open Source
 
Business 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyBusiness 101 for Developers: Time and Money
Business 101 for Developers: Time and Money
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knew
 
Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Join In With Joind.In
Join In With Joind.InJoin In With Joind.In
Join In With Joind.In
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP Stack
 
Going Freelance
Going FreelanceGoing Freelance
Going Freelance
 
Understanding Distributed Source Control
Understanding Distributed Source ControlUnderstanding Distributed Source Control
Understanding Distributed Source Control
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service Design
 
Coaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishCoaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To Fish
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Example Presentation
Example PresentationExample Presentation
Example Presentation
 
Could You Telecommute?
Could You Telecommute?Could You Telecommute?
Could You Telecommute?
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Running a Project with Github
Running a Project with GithubRunning a Project with Github
Running a Project with Github
 

Recently uploaded

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Implementing OAuth with PHP

  • 2. About Me • Lorna Jane Mitchell • PHP Consultant/Developer • Occasional writer/speaker/trainer • Twitter: @lornajane • Website: http://lornajane.net 2
  • 3. About Me • Lorna Jane Mitchell • PHP Consultant/Developer • Occasional writer/speaker/trainer • Twitter: @lornajane • Website: http://lornajane.net • I am excited about OAuth :) 2
  • 4. About This Talk • Covering OAuth1 and OAuth2 • OAuth1 needs more explanation • OAuth v1.0a is current stable • OAuth2 in use by Google, Facebook and others • Ask questions at any time 3
  • 5. About OAuth • Provider has User data • User wants data to be available to 3rd party • User tells Provider to grant access to Consumer • Access may be limited • User can revoke at any time • Provider can distinguish between User and Consumer 4
  • 6. OAuth Terminology Provider The app with the interesting data Consumer The app that wants the data User Who the data belongs to Token Random string Secret Another random string, linked to a token Verifier Another random string 5
  • 9. Dance Steps • Step 0: Register as a consumer • Step 1: Get a request token • Step 2: Send the user to authenticate • Step 3: Swap their verification for an access token • Step 4: Consume data 8
  • 10. Step 0: Register • Akin to registering for an API key • Introduce the Provider and Consumer 9
  • 11. Step 1: Get A Request Token Consumer asks for a request token from the Provider’s request token endpoint, specifying the callback URL We give the token to the user and send them to log in 10
  • 12. Step 2: User Grants Access We send the user to the Provider, with the request token, to log in 11
  • 13. Step 2: User Grants Access We send the user to the Provider, with the request token, to log in The Provider returns them to us, at the callback URL, with a verifier code 11
  • 14. Devices Where Callback Won’t Work It is hard to forward a user from a browser back to an app • Instead we use "oob" as the callback parameter • Provider displays verifier on screen • User types code into app manually 12
  • 15. Step 3: Get an Access Token Consumer makes a request to Provider’s access token endpoint with: • Consumer key • Request token • Verifier 13
  • 16. Step 3: Get an Access Token Consumer makes a request to Provider’s access token endpoint with: • Consumer key • Request token • Verifier 13
  • 18. Transmitting OAuth Parameters We have three choices: • As query parameters on the URL • Use an Authorization Header • Include the data as POST data 15
  • 19. OAuth Request Token Fields Asking for a request token looks like this: https://api.login.yahoo.com/oauth/v2/ get_request_token?oauth_nonce=ce2130523f788f313f76314ed3965ea6 &oauth_timestamp=1202956957 &oauth_consumer_key=123456891011121314151617181920 &oauth_signature_method=plaintext &oauth_signature=abcdef &oauth_version=1.0 &oauth_callback="http://yoursite.com/callback" http://developer.yahoo.com/oauth/guide/oauth-requesttoken.html We supplied the oauth_consumer_key and oauth_callback but what are these other fields? 16
  • 20. OAuth Request Token Fields • signature method: How the request is signed. Typically plaintext or HMAC-SHA1 17
  • 21. OAuth Request Token Fields • signature method: How the request is signed. Typically plaintext or HMAC-SHA1 • nonce: Cryptographic term meaning "Number Used Once". We think of a number, then throw it away 17
  • 22. OAuth Request Token Fields • signature method: How the request is signed. Typically plaintext or HMAC-SHA1 • nonce: Cryptographic term meaning "Number Used Once". We think of a number, then throw it away • timestamp: Number of seconds since the epoch 17
  • 23. OAuth Request Token Fields • signature method: How the request is signed. Typically plaintext or HMAC-SHA1 • nonce: Cryptographic term meaning "Number Used Once". We think of a number, then throw it away • timestamp: Number of seconds since the epoch • version: 1.0 in this instance (more on OAuth2 later) 17
  • 24. OAuth Request Token Fields • signature method: How the request is signed. Typically plaintext or HMAC-SHA1 • nonce: Cryptographic term meaning "Number Used Once". We think of a number, then throw it away • timestamp: Number of seconds since the epoch • version: 1.0 in this instance (more on OAuth2 later) • signature: 17
  • 25. OAuth Request Token Fields • signature method: How the request is signed. Typically plaintext or HMAC-SHA1 • nonce: Cryptographic term meaning "Number Used Once". We think of a number, then throw it away • timestamp: Number of seconds since the epoch • version: 1.0 in this instance (more on OAuth2 later) • signature: If you care, read this: http://bit.ly/gTJGPZ 17
  • 27. OAuth Tools PHP tools for OAuth: • Pecl OAuth • http://uk2.php.net/manual/en/class.oauth.php • Talk examples use this • Zend OAuth • http://framework.zend.com/manual/en/zend.oauth.html 19
  • 28. Providing and Consuming OAuth • Consuming: • relatively easy • used for authenticating against e.g. twitter • Providing: • more overhead than consuming • great way to give access to applications • needs multiple pages and endpoints as well as the API itself Provider code with dark background Consumer code with a blue background 20
  • 29. Provider: Auxiliary Web Pages There are some additional functions to provide as a provider: • Consumer signup page, like an API key • User authorisation step to allow/deny access for this consumer • Rights management page so users can control/revoke access later 21
  • 30. Provider: Step 0, Consumer Keys This is straightforward • Generate a key and a secret, store them • Return them to the consumer to use • Can use OAuth libraries, or not $hash = sha1(mt_rand()); // there are many ways to do this $consumer_key = substr($hash,0,30); $consumer_secret = substr($hash,30,10); 22
  • 31. Provider: Handling OAuth Requests With Pecl For every incoming request, for tokens and in normal operation, we’ll have code like this: $this->provider = new OAuthProvider(); // set names of functions to be called by the extension $this->provider->consumerHandler(array($this,'lookupConsumer')); $this->provider->timestampNonceHandler( array($this,'timestampNonceChecker')); $this->provider->tokenHandler(array($this,'tokenHandler')); // no access token needed for this URL only $this->provider->setRequestTokenPath('/v2/oauth/request_token'); $this->provider->checkOAuthRequest(); 23
  • 32. Step 1 consumer key, callback Consumer Provider request token, request secret 24
  • 33. Consumer: Step 1, Request Token $config = array(); $config['request_uri'] = 'http://api.local/v2/oauth/request_token'; $config['consumer_key'] = 'akey'; $config['consumer_secret'] = 'asecret'; $oauth = new OAuth($config['consumer_key'], $config['consumer_secret'] ); $oauth->setAuthType(OAUTH_AUTH_TYPE_URI); $req = $oauth->getRequestToken($config['request_uri'], "oob"); 25
  • 34. Provider: Step 1, Request Token Request • Check oauth signature and consumer key • Generate a request token and store it • Return the request token 26
  • 35. Provider: Step 1, Generate Request Token Retrieve the callback, and make the token and secret: // remember we're in URI mode parse_str($_SERVER['QUERY_STRING'], &$parameters); $callback = $parameters['oauth_callback']; $request_token = bin2hex($provider->generateToken(4)); $request_token_secret = bin2hex($provider->generateToken(12)); We then simply echo the resulting variables in query format, e.g. echo 'login_url = http://api.joindin.local/user/oauth_allow?' . 'request_token = ' . $request_token . '&request_token_secret = ' . $request_token_secret . '&oauth_callback_confirmed = true'; 27
  • 36. Storing Request Tokens Storage is simple, again, you know all this +----------------------+--------------+ | Field | Type | +----------------------+--------------+ | id | int(11) | | consumer_key | varchar(30) | | request_token | varchar(8) | | request_token_secret | varchar(32) | | callback | varchar(400) | | verification | varchar(20) | | authorised_user_id | int(11) | | created_date | timestamp | +----------------------+--------------+ 28
  • 37. Step 2, User Grants Access User grants access 29
  • 38. Provider: Step 2, Granting/Denying Access User grants access: • store user id against request token • generate a verifier code and store that too User denies access: • delete request token 30
  • 39. Step 2, For Devices Instead of forwarding the user, give them a code to use 31
  • 40. Step 3 consumer key, request token, verifier Consumer Provider access token 32
  • 41. Consumer: Step 3, Request an Access Token $oauth = new OAuth($config['consumer_key'], $config['consumer_secret']); // request token, request token secret and verification all set // by earlier steps, and loaded into $config try{ $oauth->setToken( $config['request_token'], $config['request_token_secret']); $access = $oauth->getAccessToken($config['access_uri'], null, $config['verification']); } catch (OAuthException $e) { echo $e->getMessage(); } 33
  • 42. Provider: Step 3, Generate Access Token Generate and store access token and secret, then return: echo "oauth_token=" . $tokens['oauth_token'] . '&oauth_token_secret=' . $tokens['oauth_token_secret']; 34
  • 43. Storing Access Tokens +---------------------+-------------+ | Field | Type | +---------------------+-------------+ | id | int(11) | | consumer_key | varchar(30) | | access_token | varchar(16) | | access_token_secret | varchar(32) | | user_id | int(11) | | created_date | timestamp | | last_used_date | datetime | +---------------------+-------------+ 35
  • 44. Step 4 consumer key, access token, API request Consumer Provider API response 36
  • 45. Consumer: Step 4, Subsequent Requests $oauth = new OAuth($config['consumer_key'], $config['consumer_secret']); // from the getAccessToken call $oauth->setToken($oauth_token, $oauth_token_secret); $result = $oauth->fetch("http://api.local/usual/call/here"); if($result) { $response = $oauth->getLastResponse(); } 37
  • 46. Debugging • For pecl_oauth: • Use OAuth::enableDebug() to turn on verbose debugging • The debug information is available in OAuth::debugInfo • For the provider, use OAuthProvider::reportProblem() • Wireshark or Charles Proxy • http://www.wireshark.org/ • http://www.charlesproxy.com/ 38
  • 48. 3-legged OAuth So far we have discussed 3-legged OAuth • Three parties are involved • Consumer • Provider • User 40
  • 49. 2-legged OAuth 2-legged OAuth is also an option • Only two parties involved now • Provider • User/Client • Step 0: User signs up for credentials similar to consumer key/secret • Step 4: User makes request using • their key and secret • empty token details 41
  • 50. OAuth 2 • Same principles and intention • Spec still at draft stage officially • Used by Google, Facebook and others • Aims to be less complicated than OAuth 1 • Intended to be more scalable - provider split into resources and auth servers • No signing, SSL recommended instead 42
  • 51. OAuth2 Outline +--------+ +---------------+ | |--(A)- Authorization Request ->| Resource | | | | Owner | | |<-(B)-- Authorization Grant ---| | | | +---------------+ | | | | Authorization Grant & +---------------+ | |--(C)--- Client Credentials -->| Authorization | | Client | | Server | | |<-(D)----- Access Token -------| | | | +---------------+ | | | | +---------------+ | |--(E)----- Access Token ------>| Resource | | | | Server | | |<-(F)--- Protected Resource ---| | +--------+ +---------------+ Diagram from OAuth2 spec http://tools.ietf.org/html/draft-ietf-oauth-v2-15 43
  • 52. Authorization Grant Can take many forms • Username and password • used once to obtain an access token • or just used as access token • Client credentials • client has prearranged access to the resource • Implicit • an access token provided some other way • Authorization Code • similar to OAuth 1, send user to talk to Auth Server and get verification codes 44
  • 53. Access Tokens and Refresh Tokens Refresh Tokens are an optional addition to OAuth 2 • Auth Server can return a refresh token with an access token • Refresh token has longer validity • Can be exchanged for an access token when combined with other details • Compare with re-entering your password at intervals 45
  • 54. The State of OAuth • OAuth 1 • already in use • a faff! • OAuth 2 • still being finalised • different approach to same problem 46
  • 56. Resources • PHP Manual: http://uk2.php.net/manual/en/book.oauth.php • Rasmus’ OAuth Provider Example: http://bit.ly/i76Tzx • Yahoo Developer Network Documentation: http://developer.yahoo.com/oauth/guide/ • Eran Hammer-Lahav’s blog: http://hueniverse.com • 2-legged OAuth post: http://bit.ly/ejQRoK • OAuth 2 Draft Spec: http://tools.ietf.org/html/draft-ietf-oauth-v2-15 48
  • 57. Thanks! Thanks! http://joind.in/3243/ @lornajane http://lornajane.net/ 49