oauth php app

57
Implementing OAuth

Upload: abdullah-mamun

Post on 05-Jul-2015

1.919 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Oauth Php App

Implementing OAuth

Page 2: Oauth Php App

About Me

2

• Lorna Jane Mitchell

• PHP Consultant/Developer

• Occasional writer/speaker/trainer

• Twitter: @lornajane

• Website: http://lornajane.net

Page 3: Oauth Php App

About Me

2

• Lorna Jane Mitchell

• PHP Consultant/Developer

• Occasional writer/speaker/trainer

• Twitter: @lornajane

• Website: http://lornajane.net

• I am excited about OAuth :)

Page 4: Oauth Php App

About This Talk

3

• 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

Page 5: Oauth Php App

About OAuth

4

• 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

Page 6: Oauth Php App

OAuth Terminology

5

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

Page 7: Oauth Php App

OAuth HowTo

Page 8: Oauth Php App

OAuth Dance

7

Page 9: Oauth Php App

Dance Steps

8

• 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

Page 10: Oauth Php App

Step 0: Register

9

• Akin to registering for an API key

• Introduce the Provider and Consumer

Page 11: Oauth Php App

Step 1: Get A Request Token

10

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

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

Page 12: Oauth Php App

Step 2: User Grants Access

11

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

Page 13: Oauth Php App

Step 2: User Grants Access

11

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

Page 14: Oauth Php App

Devices Where Callback Won’t Work

12

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

Page 15: Oauth Php App

Step 3: Get an Access Token

13

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

• Consumer key

• Request token

• Verifier

Page 16: Oauth Php App

Step 3: Get an Access Token

13

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

• Consumer key

• Request token

• Verifier

Page 17: Oauth Php App

OAuth Theory

Page 18: Oauth Php App

Transmitting OAuth Parameters

15

We have three choices:

• As query parameters on the URL

• Use an Authorization Header

• Include the data as POST data

Page 19: Oauth Php App

OAuth Request Token Fields

16

Asking for a request token looks like this:

https://api.login.yahoo.com/oauth/v2/get_request_token?oauth_nonce=ce2130523f788f313f763 14ed3965ea6&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 theseother fields?

Page 20: Oauth Php App

OAuth Request Token Fields

17

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

Page 21: Oauth Php App

OAuth Request Token Fields

17

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

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

Page 22: Oauth Php App

OAuth Request Token Fields

17

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

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

• timestamp: Number of seconds since the epoch

Page 23: Oauth Php App

OAuth Request Token Fields

17

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

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

• timestamp: Number of seconds since the epoch

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

Page 24: Oauth Php App

OAuth Request Token Fields

17

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

• nonce: Cryptographic term meaning "Number Used Once". Wethink 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:

Page 25: Oauth Php App

OAuth Request Token Fields

17

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

• nonce: Cryptographic term meaning "Number Used Once". Wethink 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

Page 26: Oauth Php App

Practical Examples

Page 27: Oauth Php App

OAuth Tools

19

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

Page 28: Oauth Php App

Providing and Consuming OAuth

20

• 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

Page 29: Oauth Php App

Provider: Auxiliary Web Pages

21

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

Page 30: Oauth Php App

Provider: Step 0, Consumer Keys

22

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);

Page 31: Oauth Php App

Provider: Handling OAuth Requests With Pecl

23

For every incoming request, for tokens and in normal operation, we’ll havecode 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();

Page 32: Oauth Php App

Step 1

24

Consumer Providerrequest token, request secret

consumer key, callback

Page 33: Oauth Php App

Consumer: Step 1, Request Token

25

$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" );

Page 34: Oauth Php App

Provider: Step 1, Request Token Request

26

• Check oauth signature and consumer key

• Generate a request token and store it

• Return the request token

Page 35: Oauth Php App

Provider: Step 1, Generate Request Token

27

Retrieve the callback, and make the token and secret:

// remember we're in URI modeparse_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_allo w?' .'request_token = ' . $request_token .'&request_token_secret = ' . $request_token_secret .'&oauth_callback_confirmed = true' ;

Page 36: Oauth Php App

Storing Request Tokens

28

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 |+----------------------+--------------+

Page 37: Oauth Php App

Step 2, User Grants Access

29

User grants access

Page 38: Oauth Php App

Provider: Step 2, Granting/Denying Access

30

User grants access:

• store user id against request token

• generate a verifier code and store that too

User denies access:

• delete request token

Page 39: Oauth Php App

Step 2, For Devices

31

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

Page 40: Oauth Php App

Step 3

32

Consumer Provideraccess token

consumer key,request token, verifier

Page 41: Oauth Php App

Consumer: Step 3, Request an Access Token

33

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

// request token, request token secret and verification all set// by earlier steps, and loaded into $configtry{

$oauth->setToken($config[ 'request_token' ],$config[ 'request_token_secret' ]);

$access = $oauth->getAccessToken($config[ 'access_uri' ], null,$config[ 'verification' ]);

} catch (OAuthException $e) {echo $e->getMessage();

}

Page 42: Oauth Php App

Provider: Step 3, Generate Access Token

34

Generate and store access token and secret, then return:

echo "oauth_token=" . $tokens[ 'oauth_token' ]. '&oauth_token_secret=' . $tokens[ 'oauth_token_secret' ];

Page 43: Oauth Php App

Storing Access Tokens

35

+---------------------+-------------+| 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 |+---------------------+-------------+

Page 44: Oauth Php App

Step 4

36

Consumer ProviderAPI response

consumer key,access token, API request

Page 45: Oauth Php App

Consumer: Step 4, Subsequent Requests

37

$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();}

Page 46: Oauth Php App

Debugging

38

• 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/

Page 47: Oauth Php App

Other OAuth Types

Page 48: Oauth Php App

3-legged OAuth

40

So far we have discussed 3-legged OAuth

• Three parties are involved

• Consumer

• Provider

• User

Page 49: Oauth Php App

2-legged OAuth

41

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

Page 50: Oauth Php App

OAuth 2

42

• 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 authservers

• No signing, SSL recommended instead

Page 51: Oauth Php App

OAuth2 Outline

43

+--------+ +---------------+| |--(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 spechttp://tools.ietf.org/html/draft-ietf-oauth-v2-15

Page 52: Oauth Php App

Authorization Grant

44

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 getverification codes

Page 53: Oauth Php App

Access Tokens and Refresh Tokens

45

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 otherdetails

• Compare with re-entering your password at intervals

Page 54: Oauth Php App

The State of OAuth

46

• OAuth 1

• already in use

• a faff!

• OAuth 2

• still being finalised

• different approach to same problem

Page 55: Oauth Php App

Questions?

Page 56: Oauth Php App

Resources

48

• 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

Page 57: Oauth Php App

Thanks!

49

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

@lornajane

http://lornajane.net/