My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
ConsumerHowTo  
OAuth Consumer How To
Featured, Phase-Implementation
Updated Jul 29, 2010 by brunobg%...@gtempaccount.com

OAuth Consumer

This gives an overview how you can use the oauth-php library when you want to connect to a server.

If you only need 2-legged OAuth (which is probably the most common case), see the section ConsumerHowTo#Two-legged_OAuth. There's a complete example there on how to use it.

Here are some real-life examples:

For 3-legged OAuth, the steps you need to do to get access to a server are:

  1. Get an instance of the OAuth store
  2. Add the server consumer_key and secret to the OAuth library
  3. Obtain an access token to the server
  4. Authorize the access token (exchanging it for a request token)

And now you can make signed requests to the server.

Two-legged OAuth

There's a separate store in the code for 2-legged OAuth, called OAuthStore2Leg. It does not depend on a database, and thus it's much easier to use. Here's a sample example:

include_once "oauth-php/library/OAuthStore.php";
include_once "oauth-php/library/OAuthRequester.php";

$key = '???????'; // this is your consumer key
$secret = '????????'; // this is your secret key

$options = array( 'consumer_key' => $key, 'consumer_secret' => $secret );
OAuthStore::instance("2Leg", $options );

$url = "?????????"; // this is the URL of the request
$method = "GET"; // you can also use POST instead
$params = null;

try
{
	// Obtain a request object for the request we want to make
	$request = new OAuthRequester($url, $method, $params);

	// Sign the request, perform a curl request and return the results, 
	// throws OAuthException2 exception on an error
	// $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
	$result = $request->doRequest();
	
	$response = $result['body'];
}
catch(OAuthException2 $e)
{

}

There are some real life examples in the package, including a Twitter example.

Three-legged OAuth

Step 1: Instantiate an OAuth store

Before doing any calls with the OAuth library, you need to have a store instance. oauth-php uses a singleton instance of the store for each request, so you'll have to instantiate it once yourself for the OAuth store to know which store singleton to use.

Per default oauth-php will instantiate an OAuthStoreMySQL store with default arguments for username, password and host.

For use with MySQL, you can instantiate the store like this:

$options = array('server' => 'localhost', 'username' => 'john',
                 'password' => 'secret',  'database' => 'johns_db');
$store   = OAuthStore::instance('MySQL', $options);

Step 2: Add Server To OAuth

Add the OAuth server to which you want to connect

Now, add the server to the store, this will return the consumer_key from the store, the user_id is the id of the currently logged on user.

You need to obtain the consumer key and consumer secret from the server. Every web site has a place where it is explained how you can obtain a key and secret for your application.

// Get the id of the current user (must be an int)
$user_id = 1;

// The server description
$server = array(
    'consumer_key' => 'some-server-supplied-key',
    'consumer_secret' => 'some-server-supplied-secret',
    'server_uri' => 'http://www.example.com/api/',
    'signature_methods' => array('HMAC-SHA1', 'PLAINTEXT'),
    'request_token_uri' => 'http://www.example.com/request_token',
    'authorize_uri' => 'http://www.example.com/authorize',
    'access_token_uri' => 'http://www.example.com/access_token'
);

// Save the server in the the OAuthStore
$consumer_key = $store->updateServer($server, $user_id);

List all OAuth servers

You can easily obtain a list of all registered OAuth servers. This will return an array with the full description of all servers registered for a certain user.

$servers = $store->listServers($optional_filter_text, $user_id);

Delete an OAuth server from the registry

You can simply delete an OAuth server from the registry. You need to supply the user id for which you want to delete the server.

$store->deleteServer($consumer_key, $user_id);

Step 3: Obtain Access To A Server

Before you can make OAuth signed calls to an OAuth enabled server, you have to obtain authorization from an user on that server. This can be done with the OAuthRequester class.

First we need to obtain a request token from the OAuth server. The OAuthRequester will request an instance of the OAuthStore for finding the needed uris. When you don't use the default MySQL store you will need to request an instance of the store (supplying the correct initialisation parameters) before calling the method below.

// Fetch the id of the current user
$user_id = 1;

// Obtain a request token from the server
$token = OAuthRequester::requestRequestToken($consumer_key, $user_id);

// Callback to our (consumer) site, will be called when the user finished the authorization at the server
$callback_uri = 'http://www.mysite.com/callback?consumer_key='.rawurlencode($consumer_key).'&usr_id='.intval($user_id);

// Now redirect to the autorization uri and get us authorized
if (!empty($token['authorize_uri']))
{
    // Redirect to the server, add a callback to our server
    if (strpos($token['authorize_uri'], '?'))
    {
        $uri = $token['authorize_uri'] . '&'; 
    }
    else
    {
        $uri = $token['authorize_uri'] . '?'; 
    }
    $uri .= 'oauth_token='.rawurlencode($token['token']).'&oauth_callback='.rawurlencode($callback_uri);
}
else
{
    // No authorization uri, assume we are authorized, exchange request token for access token
   $uri = $callback_uri . '&oauth_token='.rawurlencode($token['token']);
}

header('Location: '.$uri);
exit();

Step 4: Exchange Request Token For Access Token

You also have to implement a callback http handler. This is called by the OAuth server whenever the user authorized our request token. When we are authorized, then we can exchange our request token for an access token.

As an example I add an exception handler, all OAuth methods can throw OAuthException exceptions.

// Request parameters are oauth_token, consumer_key and usr_id.
$consumer_key = $_GET['consumer_key'];
$oauth_token = $_GET['oauth_token'];
$user_id = $_GET['usr_id'];

try
{
    OAuthRequester::requestAccessToken($consumer_key, $oauth_token, $user_id);
}
catch (OAuthException $e)
{
    // Something wrong with the oauth_token.
    // Could be:
    // 1. Was already ok
    // 2. We were not authorized
}

Step 5: Make A Signed Request

When you make a request to an OAuth enabled server you need to sign it with the access token and secrets we obtained when we obtained access to the server. The OAuthStore and the OAuth objects work closely together. The OAuth requester will find the correct credentials by examining the uri of the request being made. This makes signing requests very easy.

// The request uri being called.
$request_uri = 'http://www.example.com/api';

// Parameters, appended to the request depending on the request method.
// Will become the POST body or the GET query string.
$params = array(
           'method' => 'ping'
     );

// Obtain a request object for the request we want to make
$req = new OAuthRequester($request_uri, 'GET', $params);

// Sign the request, perform a curl request and return the results, throws OAuthException exception on an error
$result = $req->doRequest($user_id);

// $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
Comment by jscher...@gmail.com, Oct 2, 2008

What libs / binaries do I need to have in PHP for this to work?

Comment by project member profile....@gmail.com, Oct 2, 2008

Hi, good question.

For the full functionality you will need:

  1. PHP 5
  2. Apache extension as getallheaders() is used
  3. libcurl
  4. mysql extension
  5. openssl for RSA-SHA1 support

And for your database:

  1. MySQL with InnoDB

Comment by wmhypera...@gmail.com, Dec 2, 2008

There's a small mistake in the code here!

Under Step 2, $token is missing the closing brace.:

if (strpos($token['authorize_uri', '?'))

SHOULD BE

if (strpos($token['authorize_uri'], '?'))

Hope this saves someone some time!

Comment by project member profile....@gmail.com, Dec 3, 2008

Thank you wmhyperactive!

Corrected the typo.

Comment by jordicak...@gmail.com, Jan 29, 2009

Hello everybody,

I'm pretty new to using OAuth and, if I've understood correctly, we can choose RSA-SHA1 or HMAC-SHA1; your example here seems to use HMAC-SHA1.

The Developer's Guide (OAuth for Web Applications) says that for HMAC-SHA1 we don't need a security certificate: we can complete the registration and obtain the secret value to sign our requests.

After reading wmhyperactive's comment my doubt is: is Openssl support always required? If not, how can we sign the Signature Base String?

Thanks for your help in advance.

Comment by jordicak...@gmail.com, Jan 29, 2009

Sorry...

I meant jscherbel's question: what binaries do I need to have in PHP for this to work? When reading "5. openssl for RSA-SHA1 support", I've understood I don't need openssl for HMAC-SHA1 to work.

Thanks again for your help.

Comment by anirudh....@gmail.com, Feb 18, 2009

Was testing this code against Google OAuth endpoints. I had to change the code in step 1 to make this work :

// Save the server in the the OAuthStore
$store = OAuthStore::instance();

changed to

$mysql_options = array (
  'server'   => 'localhost',
  'username' => 'someusername',
  'password' => 'somepassword',
  'database' => 'somedatabase'
);

$store = OAuthStore::instance('MySQL',$mysql_options);

Things went fine till Step 3 here -

try
{
    OAuthRequester::requestAccessToken($consumer_key, $oauth_token, $user_id);
}

seems that in requestRequestToken of OAuthRequester.php

    $store  = OAuthStore::instance();

this line is setting a connection with the database without actually passing the parameters. This results in an error

SQL Error in OAuthStoreMySQL: No database selected SELECT ocr_consumer_key as consumer_key, ocr_consumer_secret as consumer_secret, oct_token as token, oct_token_secret as token_secret, ocr_signature_methods as signature_methods, ocr_server_uri as server_uri, ocr_request_token_uri as request_token_uri, ocr_authorize_uri as authorize_uri, ocr_access_token_uri as access_token_uri FROM oauth_consumer_registry JOIN oauth_consumer_token ON oct_ocr_id_ref = ocr_id WHERE ocr_consumer_key = 'somekey' AND oct_token_type = 'request' AND oct_token = 'sometoken' AND oct_usa_id_ref = 1 

which is triggered by

    $r    = $store->getServer($consumer_key, $usr_id);

in OAuthRequester.php .

Is anything wrong with my assumptions? Is there some additional step that I need to do? Do help.

Thanks in advance. Anirudh

Comment by adam.gre...@gmail.com, Feb 20, 2009

hey folks, isn't the reasoning off a bit in Step 2?

Step 2 assumes that the passed in $user_id registered the client; which for many cases is not what happens. Lets say I, as the owner of the app, want to allow people to interface with a google API. I setup the client, and then when a user says I want to pull my calendar into this wonderful app, I trigger the request_token, and then redirect them to the google authorization url. However, how you have it coded up, unless the user owns the oauth server, they cannot initiate the RequestToken?.

Does that make sense?

The answer is to pull back a server with the consumer_token (it should always be unique), and then when you setup a request_token, assign it to that user.

thanks, Adam

Comment by project member profile....@gmail.com, Feb 20, 2009

Hi Adam,

Thank you for you question. You are right in your observation, though it is possible to register a consumer key that is useable by all users.

To make a consumer_key accessible for all users, you have to pass the value null for the $user_id parameter in the call to updateServer. The current user has to be an administrator, an example:

// Register a new consumer_key that is accessible for all users, the current user is an admin
$consumer_key = $store->updateServer($server, null, true);

I didn't document this feature here as it would complicate the example a bit.

- Marc

Comment by oran...@gmail.com, Apr 30, 2009

If you are getting errors left & right, and you're using a MySQL store, you must initialize the store before any chunk of code that uses it.

I ran up against this because I'm doing this across multiple controllers, but had only initialized the store once. Oops.

Comment by donovan....@gmail.com, Jun 1, 2009

I didn't notice a function anywhere in the class files I could check for an access token. Something like OAuthStore->hasAccessToken($request_uri, $user_id); returns boolean OR (if you wanna code not-java style) OAuthStore->getAccessToken($request_uri, $user_id); returns false on fail, <token> on found

Comment by andrew.m...@gmail.com, Jun 20, 2009

I am stuck on the $token declaration.

I've included OAuthDiscovery, OAuthRequster, OAuthRequestVerifier, OAuthServer, and I get this error:

SQL Error in OAuthStoreMySQL: Table 'foursquare.oauth_consumer_registry' doesn't exist SELECT ocr_id FROM oauth_consumer_registry WHERE ocr_consumer_key = 'b72186f3dadb26a15ba5f20dd348c66904a241aae' AND (ocr_usa_id_ref = 1 OR ocr_usa_id_ref IS NULL)

Do I need to create separate tables in MySQL for this to work?

Comment by andrew.m...@gmail.com, Jun 21, 2009

I am just confused how oauth-php interacts with MySQL. When I var_dump $store, this is what I get:

Store data: object(OAuthStoreMySQL)#1 (2) {

["conn:protected"]=> resource(15) of type (mysql link) ["max_timestamp_skew:protected"]=> int(600)
}

Do I need to create my own tables in MySQL, or does the oauth-php library do that for me?

Comment by project member profile....@gmail.com, Jun 25, 2009

Hello Andrew,

You will need to create the table in MySQL yourself. There is a SQL script in library/store/mysql/mysql.sql There is an install.php script as well for when you can't run the install script by hand.

Regards,

Marc.

Comment by project member profile....@gmail.com, Jun 25, 2009

Hello Donovan,

Regarding a function to see if there is an access token available for a uri, you can use the function:

function getSecretsForSignature ( $uri, $user_id, $name = '' )

for that. It will throw an exception if no access token is found, otherwise it will return an array with the information needed to sign a request.

Regards, Marc

Comment by Zackatoustra, Aug 4, 2009

Hi, Sorry if that looks like an unbearable newbie who hasn't rtfm first, but... Do we always need the step 1 and 2 to connect to a server? ...

Comment by rglissm...@gmail.com, Aug 4, 2009

Does this implementation adhere to OAuth v1.0a?

Comment by project member profile....@gmail.com, Aug 4, 2009

Re: rglissmann

v1.0a support is planned for the near future.

Re: Zackatoustra

You are always free to ask :-)

You always need to initialize the OAuthStore before you can start using the OAuth library. By instantiating the OAuthStore you also initialize it.

You only need to add the server when you didn't add it before. So when you know the server is already registered you can skip step 2.

Comment by wao...@gmail.com, Aug 11, 2009

Why not put a concrete example ? // Get the id of the current user (must be an int) $user_id = 1;

// The server description $server = array(

'consumer_key' => 'some-server-supplied-key', 'consumer_secret' => 'some-server-supplied-secret', 'server_uri' => 'http://www.example.com/api/', 'signature_methods' => array('HMAC-SHA1', 'PLAINTEXT'), 'request_token_uri' => 'http://www.example.com/request_token', 'authorize_uri' => 'http://www.example.com/authorize', 'access_token_uri' => 'http://www.example.com/access_token'
); with google OAuth for example, what should I put instead of example.com? I am very confused, this class seems to be extremely usefull, but I dont know exactly how to implement it....

Comment by a4amitar...@gmail.com, Aug 17, 2009

There doesn't seem to be an easy way to adapt this for 2-legged variation of OAuth. The 2-legged OAuth doesn't require a request token or an access token. The request should be signed just using consumer key and consumer secret (using blank value for access token in signature base string, and blank value for access secret in HMAC-SHA1 algorithm key - for HMAC-SHA1 case in particular). So, this case doesn't require the complexity of OAuthStore at all; rather a simple additional constructor for OAuthRequester class that accepts request URL, HTTP Method, request params, consumer key and consumer secret should suffice. Once that's done, one can easily use this library for 2-legged OAuth scenario as well while avoiding steps 1 to 4 which aren't required for that case.

Comment by henrique...@gmail.com, Nov 2, 2009

Hi, has anyone used it with file uploading?

I was trying right now, but I didn't get anything about files in the serve-side. Also, it seems that the values aren't being processed in the OAuthRequester.php as expected.

For example, I put a "filename" and it just doesn't appear there, etc.

Comment by dhanees...@gmail.com, Dec 14, 2009

Hi Guys I am new in API field. This look very interesting. But can any one provide test database for the above code to work.

Comment by project member fiedler....@gmail.com, Jan 29, 2010

Hi, all works fine, but one question: How can i move if i already have an access token? Should i always authorize my consumer if i want to perform a server call? I think not, please give me some clues!

thx André

Comment by project member fiedler....@gmail.com, Feb 8, 2010
Step 5: Make A Signed Request

When you make a request to an OAuth enabled server you need to sign it with the access token and secrets we obtained when we obtained access to the server. The OAuthStore and the OAuth objects work closely together. The OAuth requester will find the correct credentials by examining the uri of the request being made. This makes signing requests very easy.

Thx! :o)

Comment by freeklij...@gmail.com, Feb 17, 2010

In the addServerToken function of OAuthStoreMySQL.php the server id is aquired trough the following query:

$ocr_id = $this->query_one('
	SELECT ocr_id
	FROM oauth_consumer_registry
	WHERE ocr_consumer_key = \'%s\'
		', $consumer_key);

Googles OAuth implementation supports non-registered applications to be allowed to interact with its API's by using "anonymous" as consumer key and consumer secret. In this case multiple users can be associated with the same consumer key resulting in the first server found in above query being used while inserting token.

I don't know if this is a bug or me using the wrong constructs but I hope someone can clarify this for me.

Comment by project member brunobg%...@gtempaccount.com, Feb 18, 2010

@freeklijten: you are right. My guess is that the original writers didn't think of this case, but to me it's a bug, because you can have multiple equal consumer_keys. Do you think that the pair (consumer_key, server_uri) is unique? It seems so to me; if you confirm, I can kill this one.

Comment by Erez.hoc...@gmail.com, Mar 1, 2010

im getting an error using the 2leg example, it looks for a file i dont have called "OAuthStore2Leg.php", anyone else had this ?

Comment by Erez.hoc...@gmail.com, Mar 1, 2010

also, while trying the three legged with google i keep getting " Fatal error: Class 'OAuthSignatureMethod' not found in /bla/bla/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php on line 33" error, must be smthing wrong with my require's but i cant figure it out.

Comment by quickred...@gmail.com, Mar 2, 2010

@Erez That file is not in the tarball, download the source from svn

Comment by dim.dims...@gmail.com, Mar 3, 2010

I'm new to this stuff and I think there isn't any clear information on how to set this up. I have questions like:

- what are the server URL's to call (OAuthRequest.php); - how to run an install the server.

It seems this code is great but why isn't there a complete setup instruction and three legged client sample.

Has anyone done this successful?

Comment by pengkong, Mar 5, 2010

yep i've done this successfully using codeigniter framework. And both client and server works in less then 200 lines php code.

i must admit it's hard to implement and I only succeeded after studying andy smith's implementation (http://oauth.googlecode.com/svn/code/php/) in great detail. Andy's implementation is easier to understand because he doesn't implement the database for you which reduces complexity.

After understanding and implementing that, this will becomes much easy to implement.

There isn't any detailed documentation on implementing OAuth in PHP, at least not that i could find. You really have to dive in and understand the codes to be able to do it.

Ok here are the steps anyway:

Part 1 - Create the "store" and "server" objects

1) require 3 files... OAuthRequester.php, OAuthServer.php and OAuthStore.php 2) Create the "store" using OAuthStore::instance(); 3) Create the "server" using new OAuthServer();

If you can complete part 1... you won half the battle :p

Part 2 - Set up consumer

1) Create a consumer with the server ($store->updateConsumer and $store->getConsumer) 2) Save the consumer ($store->updateServer and $store->getServer)

Part 3 - Get request token

1) Use OAuthRequester::requestRequestToken() to get the request token 2) Make sure you setup your request token endpoint with $server->requestToken(); 2) Redirect to authorization endpoint with request token

Part 4 - Authorize request token

1) Use $server->authorizeVerify() and $server->authorizeFinish(); 2) Redirect back to callback url

Part 5 - Get Access Token

1) Use OAuthRequester::requestAccessToken()

wola! you have the access tokens...

Comment by project member brunobg%...@gtempaccount.com, Mar 11, 2010

I'm preparing a three-legged example and will add it to the package soon.

Comment by sci...@gmail.com, Mar 30, 2010

thanks for the library, trying to make it work using RSA-SHA1 signature with 2Leg, not going so well so far, any help appreciated.

BTW class "OAuthSignatureMethod_RSA_SHA1" is missing the following require_once: require_once dirname(FILE).'/OAuthSignatureMethod.class.php';

thanks andrea

Comment by psg...@gmail.com, Apr 2, 2010

I ran into the same problem as freeklijten's, in which multiple users could not be tied to one consumer. A quick fix solved the problem. Change the code (can be found around line 328 of OAuthStoreMYSQL): {{{$ocr_id = $this->query_one('

SELECT ocr_id FROM oauth_consumer_registry WHERE ocr_consumer_key = \'%s\' ', $consumer_key); }}}

To:

{{{$ocr_id = $this->query_one('SELECT ocr_id

FROM oauth_consumer_registry WHERE ocr_usa_id_ref = %d', $user_id);

Comment by project member brunobg%...@gtempaccount.com, Apr 28, 2010

@scieck: fixed. Thanks, but next time please post bugs in the issues page.

Comment by powell....@gmail.com, Apr 30, 2010

Just wondering how you pass over the oauth_verifier parameter with the requestAccessToken method? Trying to gain access token from Twitter and am receiving an 'Invalid oauth_verifier parameter' error.

Comment by project member fiedler....@gmail.com, May 8, 2010

I´ve fixed  issue #37  and  issue #38  by "hand" and tested server/client again. Now i get this message:

OAuth Verification Failed: Can't exchange request token "30de489cc2038bdc49953eebe0e33b7e04be59dba" for access token. No such token or not authorized

The user IS authorized! The callback url looks like this:

http://api-test.xyz.com/callback.php?consumer_key=0d9dafb6fc5f36174f4f15e957cf67cf04be488ad&usr_id=1&oauth_token=30de489cc2038bdc49953eebe0e33b7e04be59dba&oauth_verifier=11fcd850b7

Here´s the contents of the callback.php script:

http://gist.github.com/394670

The oauth_consumer_registry table looks like this:

(ocr_id, ocr_usa_id_ref, ocr_consumer_key, ocr_consumer_secret, ocr_signature_methods, ocr_server_uri, ocr_server_uri_host, ocr_server_uri_path, ocr_request_token_uri, ocr_authorize_uri, ocr_access_token_uri, ocr_timestamp)

VALUES

(1, 1, '0d9dafb6fc5f36174f4f15e957cf67cf04be488ad', '6c5bc5f6557f4e28de8134df0167d6e3', 'PLAINTEXT', 'http://www.xyz.com/', 'www.xyz.com', '/', 'http://www.xyz.com/oauth/request_token', 'http://www.xyz.com/oauth/authorize', 'http://www.xyz.com/oauth/access_token', '2010-05-08 19:22:00');

All other client tables are empty.

Now, how to fix this?

Thanks, André

Comment by mambena...@gmail.com, May 8, 2010

I used it with kohana php and I configured the database and included all works well but when I run STEP 3 with Google API it shows me error? No answer from the server "https://www.google.com/accounts/OAuthGetRequestToken" while requesting a request token [/error]

Comment by mambena...@gmail.com, May 8, 2010

can somebody please tell me how to use this example with Google Data API, I am going nuts here...spent the whole day trying to figure out this oauth thing

Comment by kinl...@gmail.com, May 9, 2010

I was getting an error where my response wasn't even coming back. I was making a call to an https:// oauth API.

I am running PHP on Windows 2003.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Needs to be set.....for it to work.

Comment by project member fiedler....@gmail.com, May 15, 2010

Are there any news about comment "Comment by fiedler.andre, May 08, 2010" ? I really don´t know how to fix this "issue". I´ve checked out #127 ... issue persists.

Comment by project member fiedler....@gmail.com, May 17, 2010

I really don´t get it. If you take the ClientHowTo? and ServerHowTo and build a test server and a test client with r127, can you verify that authorize and making a signed request is working? If that´s true, can you put both client and server into the repository? Would be a good starting point for me to bugfix. I think i did everything correct, but still got "not authorized" after authorizing. :(

Comment by satyadee...@gmail.com, May 31, 2010

what happens if i dont knw the user id before hand, i know it only after authorisation??

Comment by sty...@gmail.com, Jun 10, 2010

@satyadeep.1991: I believe the userid is meant to be from your own application/system, and not one from a service.

Comment by cezar.elnazli@gmail.com, Jun 14, 2010

How can I change the database driver to MySQLi? Thanks in advance!

Comment by simon.re...@gmail.com, Jun 14, 2010

Hello, at r130, some tests are failing for me.

$ php oauth_test.php ...

Assertion failed in /Users/simonreekie/Tmp/oauth-php-130/test/oauth_test.php:90

$req->getNormalizedParams() == 'a=x%20y&b=x%21y'
... Assertion failed in /Users/simonreekie/Tmp/oauth-php-130/test/oauth_test.php:106
$req->signatureBaseString() == 'POST&https%3A%2F%2Fphotos.example.net%2Frequest_token&oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dhsu94j3884jdopsl%26oauth_signature_method%3DPLAINTEXT%26oauth_timestamp%3D1191242090%26oauth_version%3D1.0'

Anyone else seeing this? This doesn't happen in r98 which I am using successfully at the moment - but I'd really like to use the version that supports 1.0a...

Comment by project member fiedler....@gmail.com, Jun 14, 2010

@simon.reekie

Can you file an issue for this in the issues section? I think it will get lost in this wiki... ;o)

Comment by project member fiedler....@gmail.com, Jun 14, 2010

@simon.reekie

You have to instanciate the Store with MySQLi parameter:

$store = OAuthStore::instance('MySQLi', $options);
Comment by project member fiedler....@gmail.com, Jun 14, 2010

ups... i did mean @cezar.elnazli in my last comment! Sry simon! ;o)

Comment by simon.re...@gmail.com, Jun 15, 2010

Np Andre :-) I've filed an issue for the failing tests.

Comment by simon.re...@gmail.com, Jul 22, 2010

Cross-posted from ServerHowTo, apologies... -- Hi, I'm trying to get twolegged OAuth to work against my OAuth server. My first confusion is that in twoleggedtest.php, the url being accessed is the 'request_token' endpoint:

$key = 'key'; // fill with your public key $secret = 'secret'; // fill with your secret key $url = "http://term.ie/oauth/example/request_token.php"; // fill with the url for the oauth service

Is that correct? Can it not be set directly to a '$server->verifyIfSigned()' wrapped page on my server?

So when I do change the url in the example to go directly to my page I can only get that page to work if I call '$server->verifyIfSigned(false)', ie. a token_type of false.

In this way i'm not able to call the same page in both normal three legged and two legged!?

Has anyone got this to work? I am quite certain I might be just not understanding the twolegged use correctly of course :-)

Thanks.

Comment by pol...@gmail.com, Aug 2, 2010

Hello everyone.

How use xoauth_requestor_id in this library for 2-legged OAuth? I want to access to http://www.google.com/calendar/feeds/default/private/full. It is a google apps calendar, and i must use 2-legged OAuth.

Help me, please!

Comment by powell....@gmail.com, Aug 23, 2010

Hi - I'm attempting to use oauth-php with Googles OAuth API. However, when it comes to requesting an access token I'm finding the two legged approach is encoding the token twice, causing malformed tokens and resulting in them being rejected by Google.

The problem comes here:

$params = array(

'oauth_token' => OAuthRequest::urldecode($GET['oauth_token']), 'oauth_verifier'=> OAuthRequest::urldecode($GET['oauth_verifier'])
);

$oauth = new OAuthRequester(ACCESS_URI, 'GET', $params);

When the token is passed into the OAuthRequester constructor, it is passed to the OAuthRequestSigner constructor, which then sets the parameters and encodes them.

The problem comes to when the request gets signed on line 131 of OAuthRequestSigner.php:

$this->setParam('oauth_token', $token);

The token is again set as a parameter causing any encoded characters (encoded by the constructor) to be re-encoded causing malformed tokens.

Comment by tdave...@gmail.com, Sep 1, 2010

Before OAuth i Googled "post to twitter using PHP". The first hit gave me a few lines of code. I copied its 5 or 6 lines, populated $username, $password, and $message. I ran it. It posted.

This crap here? I have no idea what it's even talking about.

Can anyone point me to 5 or 6 lines of code I can paste to make PHP post to Twitter now?

Comment by niwa3...@gmail.com, Sep 5, 2010

tdave365, i am new to all of this and probably starting my code at the right (or wrong) point. See the API pages of twitter for the message "August 31, 2010 Basic Auth has been deprecated. All applications must now use OAuth. Read more »" .... thats why I am here on this page, maybe you are too! Still cant get it working

Comment by mvenkat...@gmail.com, Sep 21, 2010

I really like this library vs. other ones I have found since it has a great mechanism for storing OAuth credentials. Has anyone out there made a patch to bring support up to OAuth 1.0a or does anyone know what the status of this planned support is? Good job on the library in any case.

Comment by project member brunobg%...@gtempaccount.com, Sep 21, 2010

Oauth 1.0a is already supported.

Comment by mimearts...@gmail.com, Oct 9, 2010

There is no curl here. How do I use the script for twitter?

Comment by nmaste...@gmail.com, Nov 4, 2010

The examples/documentation here is completely wrong for 1.0a use, and I was convinced the library was incompatible for a long time before I figured out how it wanted things passed around.

For OAuth 1.0a, you DO NOT pass the callback via url as the current example shows, but via curl while getting the request token. So in step 3 your call will become $token = OAuthRequester::requestRequestToken($consumer_key, $user_id, array('oauth_callback' => $callback_uri));

You must then get the oauth_verifier and include it in the access token request, like so: OAuthRequester::requestAccessToken($consumer_key, $oauth_token, $user_id, 'POST', $_GET['oauth_verifier']);

Hope that saves some people the ridiculous amount of time it took me to realize this.

Comment by adammine...@gmail.com, Nov 20, 2010

I keep throwing:

CURL error: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Although, when I visit the API url in chrome, it claims the certificate is valid (signed by VeriSign?), where should I begin to look for issues?

Comment by arievand...@gmail.com, Nov 25, 2010

oauth-php-super-easy-example.zip

After spending 3 days testing different libs to get oauth to connect to Twitter, I setup a (hopefully) very easy example based on andy smith's implementation (http://oauth.googlecode.com/svn/code/php/). I hope that this will save others a lot of hours of work to just see it in action.

My goal was to setup a complete example that would just work without a lot of fuss.

It uses CURL to process all outbound calls to Twitter, so make sure your OS has it installed. Tested with php v5.3.3. Make sure you open up both client.php and common.inc.php and change the include paths as needed.

get it here: https://docs.google.com/leaf?id=0B0FXNCj3-C0AYjgwYWQzY2YtN2VjYi00N2Y1LWJkNjQtM2I0ODBiZDU3MTI5&hl=en

Comment by willow...@gmail.com, Dec 30, 2010

Hi Arievanderberg,

I believe your script is for web client, do you have one for pin-based server client?

Thanks

Comment by sonawane...@gmail.com, Jan 5, 2011

@ arievandenberg : i am getting following error in you clinet.php code

"SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed"

when i print curl_error for "request_token" action..

Also, im getting same error for oauth-php\example\twoleggedtwitter.php

I m running code from my localhost but i have made host entry for the callback domain(of callback url) that i have registered with Twitter and passing same consumer key and consumer secret that twitter gave me upon registration of app.

Am i doing something wrong over here..why is this error..??

please help

Comment by sonawane...@gmail.com, Jan 6, 2011

Ok i have resolved that issue.related curl and ssl thingy

Comment by stalker...@gmail.com, Jan 13, 2011

Is there any way to do the 3-legged without setting up a MySQL database and just using some temp memory for the store?

Comment by hemerson...@gmail.com, Feb 8, 2011

Hi.

I'm using the library oauth-php for use this API: http://developer.trademe.co.nz/

I have connected, also got the access token and got information through API.

But now I need to send information to API, I need to send a XML String for web request.

With oauth-php I can do it? Can I use OAuthRequester method to send the XML via web request?

Somebody can show me an example how I can send XML with OAuthRequester?

URL: https://api.trademe.co.nz/{version}/Listings/{listing_id}/questions/{question_id}/answerquestion.{file_format}

XML: <code><ListingAnswerQuestion xmlns="http://api.trademe.co.nz/v1"> <answer>Yes it does blend.</answer> </ListingAnswerQuestion> </code>

Link Method: http://developer.trademe.co.nz/api-documentation/listing-methods/answer-question/

Kind regards.

Hemerson.

Comment by harna...@students.lgu.edu.lb, Mar 9, 2011

Hello :)

I implemented the same code as given in the example, however im getting this error after the first register goes fine, the second time I run the code it gives this:

Fatal error: Uncaught exception 'OAuthException2' with message 'Unexpected result from the server "https://www.google.com/accounts/OAuthGetRequestToken" (400) while requesting a request token' in /home/hisham-a/public_html/x/newsys/files/gmail/apigoogle/lib/OAuthRequester.php:169 Stack trace: #0 /home/hisham-a/public_html/x/newsys/files/gmail/apigoogle/index.php(21): OAuthRequester::requestRequestToken('students.lgu.ed...', '1') #1 {main} thrown in /home/hisham-a/public_html/x/newsys/files/gmail/apigoogle/lib/OAuthRequester.php on line 169

I really need help in applying a MySQL storage rather than the Session one, though I dont have problems in implementing the Session storage, works like a charm.

I Appreciate the help

Hisham

Comment by harna...@students.lgu.edu.lb, Mar 9, 2011

So I managed to make it work, but after it registers the consumer key in the db, i started to get this error, which doesn't go until I delete the value from the database:

Fatal error: Uncaught exception 'OAuthException2' with message 'The server with key "domain.com" has already been registered' in /home/hisham-a/public_html/x/newsys/files/gmail/apigoogle/lib/store/OAuthStoreSQL.php:782 Stack trace: #0 /home/hisham-a/public_html/x/newsys/files/gmail/apigoogle/index.php(19): OAuthStoreSQL->updateServer(Array, '1') #1 {main} thrown in /home/hisham-a/public_html/x/newsys/files/gmail/apigoogle/lib/store/OAuthStoreSQL.php on line 782

how is it supposed to work ?

regards,

hisham

Comment by ulasari...@gmail.com, Apr 6, 2011

Hi. I have to get access for 2 or more APIs. I changed the googledocs.php example file like;

$getAuthTokenParams = array('scope' =>
'http://docs.google.com/feeds/ http://www.google.com/calendar/feeds/ http://www.google.com/m8/feeds/', 'xoauth_displayname' => 'xxx', 'oauth_callback' => 'http://xxx/googledocs.php');
$request = new OAuthRequester("http://docs.google.com/feeds/default/private/full/", 'GET', $tokenResultParams);

The grant access page is working well I got the token. But when it returns back to googledocs.php again, it gives me:

Request failed with code 400: Invalid request URIobject(OAuthException2)#4 (7) { ["message":protected]=> string(49) "Request failed with code 400: Invalid request URI"

I also tried to fetch data with only one API access. There was no problem. Can you please help me?

Comment by channelv...@gmail.com, Apr 13, 2011

RE: You always need to initialize the OAuthStore before you can start using the OAuth library.

Can someone provide an example of what needs to be done here? I have the MySql? database created and I'm looking for sample/example code to run as a next step. Thanks

Comment by theorigi...@gmail.com, Apr 16, 2011

running oauth-example.php and getting 500 error which states "no server with consumer key xxxx has been registered". Do I need to enter this info outside the program? Or is some other function failing (no other errors reported; sql logs are clean too.

Comment by pdar...@gmail.com, May 13, 2011

I've encountered and gotten past a number of errors, but I'm stuck on this one:

Fatal error: Uncaught exception 'OAuthException2' with message 'The server with key xxxx has already been registered' in C:\xampp\htdocs\oauth-php\library\store\OAuthStoreSQL.php:782 Stack trace: #0 C:\xampp\htdocs\oauth-php\example\client\fitbitoauth.php(27): OAuthStoreSQL->updateServer(Array, 1) #1 {main} thrown in C:\xampp\htdocs\oauth-php\library\store\OAuthStoreSQL.php on line 782

Any suggestions anyone?

Comment by vin...@dakinegroup.com, May 31, 2011

i could get it to work finally, took few hours. It might be a good idea to refer to the sample program lying in the oauth-php that one can use to test concepts.

Those who are trying it for the first time, please note that there are nuances specific to versions of oauth and additional parameters required by different service providers. Nevertheless, the library provides optional arguments to deal with it.Refer to Comment by nmaste...@gmail.com, Nov 4, 2010 above for one such change. I have tried google, yahoo and here are key diffferences that i could see till now:

Google:

a request token from the server. You would require optional argument to provide scope parameter for google
$token = OAuthRequester::requestRequestToken($consumer_key, $user_id, array('scope' => "https://www.google.com/m8/feeds/contacts/default/full/"));

Yahoo $token = OAuthRequester::requestRequestToken($consumer_key, $user_id, array('oauth_callback' => 'http://netucation.co.in/ef'));

I am exploring: when server allows user to authenticate with google, how to get this "userid" in case of multiple such users coming to my server. There would be cases, who won't complete the authentication and leave it in between. Example quoted here requires userid at the begining, when our program does not know whether the user is a new one or an existing one or whether he/she would complete authentication (ghost). Have couple of threads, will update more when i conclude.

Comment by ferret1...@gmail.com, Jun 29, 2011

Hi, Would appreciate help on this one. I am working in a situation where I have to use this oauth library, and the access token is stored in custom table (it has to be like this) rather than the default ones using OauthStoreMysql?. I am using OauthStoreSession? to get the access token and save it to my database.

I am having problems doing the final part of oauth, getting user info. Is there a way I can plug in the access tokens I already have into this code and send it off to retrieve user info? Im trying it on twitters api.twitter.com/1/account/verify_credentials.json at the moment.

Basically I already have an access token stored in a string, and I want to get user info!

Thanks in advance!

Comment by necro...@gmail.com, Jul 9, 2011

When using three legged oauth it is important that you do not include oauth-php/library/OAuthRequester.php before you have stored the new server.

It would be nice if you also mentioned that you have to import oauth-php/library/store/mysql/mysql.sql before creating the server.

Comment by matteopa...@gmail.com, Sep 10, 2011

is PUT supported?

Comment by lokegu...@gmail.com, Oct 3, 2011

Can I use same library for facebook and other provider as well?

Comment by andre.la...@gmail.com, Feb 5, 2012

I have checked the included examples for twitter and GDocs OAuth and found some minor issues which I want to list for all who are interested (partly already discussed in the Issue Tracker section):

- twitter 2-legged oauth doesn't seem to work any longer for querying Twitters public_timeline.json, Twitter states here that not more than XXX anonymous requests per day are allowed. However, the 3-legged oauth version (with authentication) works for me. You only have to pay attention that you do not include additional $getAuthTokenParams in the requestRequestToken step (as e.g. in the GDocs example), otherwise the Twitter API call will fail

- If you use the 3-legged GDocs example together with a MySQL Store, the server_uri for the OAuth Store initialization must match the API domain you want to query later. In the example, https://google.com is used instead of https://docs.google.com/feeds/. As a result, no access tokes will be found within the Store although the OAuth Handshake worked fine.

- If you use a MySQL OAuth Store, the $store->updateServer() call will always raise an exception if you load the page for the second time (e.g after OAuth authentication redirects the user back to your application webpage). I wrapped a try catch block around it which suppresses the warning. With that, everything works fine.

- If you use a Session Store (by default), pay attention to clear the old OAuth SESSION content before starting a new OAuth Handshake. I had problems doing consecutive OAuthentication for multiple applications within one browser session.

Nevertheless, oauth-php is a great library!

André

Comment by plokoonm...@gmail.com, Apr 24, 2012

Hi, To make signed requests having already stored the access token and secret, you just need to do this:

$store = OAuthStore::instance('Session', $server); //server description $store->addServerToken($CONSUMER_KEY, $token_type, $ACCESS_TOKEN, $ACCESS_TOKEN_SECRET, $user, $options=array());

Hope this will be useful for somebody :)


Sign in to add a comment
Powered by Google Project Hosting