My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
ServerHowTo  
Quick How To for OAuth enabling a server
Featured, Phase-Implementation
Updated May 6, 2010 by brunobg%...@gtempaccount.com

Introduction

Adding OAuth authentication to your server is very easy. You will need to check the incoming requests for any OAuth authentication details. Some simple templates will be needed to handle the authorization of request tokens and for handling requests for access tokens.

You will need a couple of controllers:

  1. oauth_register.php to let an user obtain a consumer key and secret.
  2. request_token.php to return a request token.
  3. authorize.php to let the user authorize a request token.
  4. access_token.php to exchange an authorized request token for an access token.

OAuthStore

In the examples below I assume that you use the default MySQL store for the OAuth credentials. You can select another store by first requesting an OAuthStore instance with a parameter telling which store is needed:

$store = OAuthStore::instance('mystore');

This assumes that you have a file OAuthStoremystore.php in the store directory. You can check the OAuthStoreMySQL.php for an example implementation.

Checking A Request For Authorization

At the start of every request handled by your application you can check if the request contains OAuth authorization information.

if (OAuthRequestVerifier::requestIsSigned())
{
	try
	{
		$req = new OAuthRequestVerifier();
		$user_id = $req->verify();

		// If we have an user_id, then login as that user (for this request)
		if ($user_id)
		{
			// **** Add your own code here ****
		}
	}
	catch (OAuthException $e)
	{
		// The request was signed, but failed verification
		header('HTTP/1.1 401 Unauthorized');
		header('WWW-Authenticate: OAuth realm=""');
		header('Content-Type: text/plain; charset=utf8');
					
		echo $e->getMessage();
		exit();
	}
}

Controller 1. oauth_register.php obtain consumer key and secret

Every consumer uses a combination of a consumer key with a consumer secret and a token with a token secret to sign its requests. An user must first obtain a consumer key with a consumer secret before (s)he can start requesting access to the server.

// The currently logged on user
$user_id = 1;

// This should come from a form filled in by the requesting user
$consumer = array(
    // These two are required
    'requester_name' => 'John Doe',
    'requester_email' => 'john@example.com',

    // These are all optional
    'callback_uri' => 'http://www.myconsumersite.com/oauth_callback',
    'application_uri' => 'http://www.myconsumersite.com/',
    'application_title' => 'John Doe\'s consumer site',
    'application_descr' => 'Make nice graphs of all your data',
    'application_notes' => 'Bladibla',
    'application_type' => 'website',
    'application_commercial' => 0
);

// Register the consumer
$store = OAuthStore::instance(); 
$key   = $store->updateConsumer($consumer, $user_id);

// Get the complete consumer from the store
$consumer = $store->getConsumer($key);

// Some interesting fields, the user will need the key and secret
$consumer_id = $consumer['id'];
$consumer_key = $consumer['consumer_key'];
$consumer_secret = $consumer['consumer_secret'];

When you want to update a previously registered consumer, then supply the id of the consumer, the consumer_key and the consumer_secret. The key and secret can not be changed and are used as extra verification during the update.

Requesting a list of registered consumers

You can fetch a list of all consumers currently registered by a certain user:

// The currenly logged on user
$user_id = 1;

// Fetch all consumers registered by the current user
$store = OAuthStore::instance();
$list = $store->listConsumers($user_id);

Controller 2. request_token.php return a request token

After the consumer got a consumer key and secret it can request a request token for obtaining user authorization.

$server = new OAuthServer();
$token = $server->requestToken();
exit();

Controller 3. authorize.php user authorization of a request token

This controller asks the user if it allows the consumer to access his account. When allowed then the consumer can exchange his request token for an access token.

You have to make sure that an user is logged on when accessing the code below.

Note The OAuthServer uses the $_SESSION to store some OAuth state, so you must either call session_start() or have automatic session start enabled.

// The current user
$user_id = 1;

// Fetch the oauth store and the oauth server.
$store  = OAuthStore::instance();
$server = new OAuthServer();

try
{
    // Check if there is a valid request token in the current request
    // Returns an array with the consumer key, consumer secret, token, token secret and token type.
    $rs = $server->authorizeVerify();

    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        // See if the user clicked the 'allow' submit button (or whatever you choose)
        $authorized = array_key_exists('allow', $_POST);

        // Set the request token to be authorized or not authorized
        // When there was a oauth_callback then this will redirect to the consumer
        $server->authorizeFinish($authorized, $user_id);

        // No oauth_callback, show the user the result of the authorization
        // ** your code here **
   }
}
catch (OAuthException $e)
{
    // No token to be verified in the request, show a page where the user can enter the token to be verified
    // **your code here**
}

Controller 4. access_token.php exchange authorized request token for an access token

This exchanges an authorized request token for an access token. The access token (and associated secret) can be used to sign requests.

$server = new OAuthServer();
$server->accessToken();

The OOB

OAuth defines "OOB" (Out-Of-Band). This can be used for applications that do not have a callback, such as mobile phones.

If you are getting a redirection to a URL such as http://oob/?oauth_token=xxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxx, a sure solution is to set the 'oauth_callback' parameter in the query parameters.

Comment by cam.la...@gmail.com, Mar 5, 2009

With the last version, some errors typo.

getConsumer method require two arguments id_consumer and id_user. return remove '''osr''' prefix.

Controller 1. oauth_register.php

// Register the consumer
$store = OAuthStore::instance(); 
$key   = $store->updateConsumer($consumer, $user_id);

// Get the complete consumer from the store
$consumer = $store->getConsumer($key,$user_id);

// Some interesting fields, the user will need the key and secret
$consumer_id = $consumer['id'];
$consumer_key = $consumer['consumer_key'];
$consumer_secret = $consumer['consumer_secret'];
Comment by cam.la...@gmail.com, Mar 5, 2009

controller 3. authorize.php

i don't understand this line : if ($_SERVER['REQUEST_METHOD'] == 'POST')

'''OAuthServer''' use '''GET''' as default '''REQUEST_METHOD'''

Comment by Cenji.Ne...@gmail.com, Apr 7, 2009

Thanks for the code & explanation! I'm just researching OAuth for use for access to a web-service API we provide.

Q: Our API currently has some medium-grained access controls that I'd like to expose such that the consumer can ask the user (resource owner) specifically what sub-set of access is being requested (and hence granted by the access token). What is the best way to do that? Is there a recommended OAuth way?

To make it concrete, suppose, hypothetically, I was a photo store service and wanted to a allow consumer site access to my users/customers photos (e.g. a printing site). However, suppose my customers organize photos into named groups and would only want to grant the consumer site access to one named group of photos, not access to all photos.

When developing the server OAuth implementation, should I specify in the API documentation that the access to /authorize.php should additionally contain a form field named "photo_group", for example? Then in authorize.php I'd just display the requested group for the user and generate an access token that is only valid for access to that group?

Comment by Cenji.Ne...@gmail.com, Apr 7, 2009

@cam.lafit - as I understand it, the authorize.php page is being accessed by the user/resource-owner's browser to ask them if the service should allow access to the consumer site. Hence, the POST is presumably when the user clicks the 'allow' button to give the ok. If it is accessed using GET, it should just show text and form prompting the user to 'allow' the providers request. (right?)

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 ibnba...@gmail.com, May 27, 2009

i have few question if you can answer it please.

1) can i use this library standalone without cms? 2) can you show how to get a request token, with access token and authorize, because when i try to get request token, its giving me error on everytime and i think im not doing things properly, so can you show example please.

Comment by ronn.ab...@gmail.com, Jul 2, 2009

@Cenji.Neutra

To allow granular access, have a permissions column where you store your request/access tokens server side. After the user is authenticated and is on the authorize.php page, have a form where the user chooses which permissions (or in your example, photo groups) the current token has access to. Upon submission, store the approved permissions in your permissions column (as a serialized array for example) for the token.

Your web service's token may have the following columns: token_key, token_secret, type, consumer_key, authorized, user_id, permissions

When your web service receives a request from a consumer site, validate the request by checking what permissions the access token have access to.

Comment by dvanbr...@gmail.com, Jul 30, 2009

I'm a bit new to oauth. Can someone please clarify how the "server" example in this code source is meant to work? I looks as though when registering....you are registering a "server" and not a "consumer"? I thought the point of a "server" was to register and feed to consumers so why in the server example does it register a server? I think I'm just missing a small point here that is having a huge impact.

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

@dvanbrunt

You are registering a consumer at the server. As you this example shows a server it is using the OAuthServer object. A server handles consumers, so it is registering and querying for consumers in the OAuthStore.

Comment by dvanbr...@gmail.com, Aug 10, 2009

@profile.url ...or anyone that might know the answer... is there a reason that in the "OAuthStoreMySQL.php" (around line 1212) that the "ost_usa_id_ref" is hardcoded to "1"? Is this not supposed to be the currently logged in users id? or the user/owner of the key and secrets userid?

Comment by henrique...@gmail.com, Aug 22, 2009

Isn't it a security flaw not to have a method to display what request tokens an user has so he/she can safely avoid a server to get access to the account after giving authorization, but the server not requesting the access tokens (so the end user isn't in a condition that can't just opt out from giving access before the consumer asking for an exchange)?

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

Hi Henrique,

I am not totally sure what you are asking. However, the OAuthStore does implement methods to list and manage the access tokens of a particular user. You will need to write your own interface routines to use these methods.

- Marc

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

@dvanbrunt,

The id is hard coded to '1' because the server does not know the user id yet. The request token is requested with a server to server connection, without interaction of the user agent. So the user cookie is not included in the request and the server just assigns a dummy value to the user id. This could be any id as long it valid (think of foreign key constraint checks).

- Marc

Comment by henrique...@gmail.com, Aug 25, 2009

profile.url, when the user authorizes the third party (consumer) before this third party exchanging the request token for a access token afaik there is no method to be used to let the user go back and cancels the request token so he can avoid the third party to get an access token.

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

@henriquevicente

You are right. There is no such method. When you like to have them, then please add a ticket, so that we can look at it when we dive into the 1.0a support.

The library was designed with server-to-server communication in mind, that means that after authorizing the request token the token will almost immediately be exchanged for an access token.

- Marc

Comment by glenhass...@gmail.com, Oct 11, 2009

Shinig seems to be attaching a trailing & to the uri with a signed request. This casued RSA_SHA1 signatrue verification to not work. I implemented a fix by not adding the paramater with an empty name in OAuthRequest, parseUri but there is probably a better way.

Comment by fradj.jo...@gmail.com, Nov 6, 2009

I think there are a couple of problems with MD5 and HMAC_SHA1 classes.

"verify" methods of the two classes do not compare the decoded values

        // MD5
        public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature )
        {
                $a = $request->urldecode($signature);
                $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret));

                // We have to compare the decoded values
                $valA  = base64_decode($a);
                $valB  = base64_decode($b);

                // Crude binary comparison
                return rawurlencode($a) == rawurlencode($b);

                //FIXME should be return rawurlencode($valA) == rawurlencode($valB);
        }

         // HMAC_SHA1
        public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature )
        {
                $a = $request->urldecode($signature);
                $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret));

                // We have to compare the decoded values
                $valA  = base64_decode($a);
                $valB  = base64_decode($b);

                // Crude binary comparison
                return rawurlencode($a) == rawurlencode($b);

                //FIXME should be return rawurlencode($valA) == rawurlencode($valB);
        }

Moreover the signature method of MD5's class define an unsed variable s and doesn't add the consumer_secret and the token_secret to the Signature Base String

        function signature ( $request, $base_string, $consumer_secret, $token_secret )
        {
                $s  .= '&'.$request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret);
                $md5 = md5($base_string);
                $bin = '';
                
                for ($i = 0; $i < strlen($md5); $i += 2)
                {
                    $bin .= chr(hexdec($md5{$i+1}) + hexdec($md5{$i}) * 16);
                }
                return $request->urlencode(base64_encode($bin));
        }

I think the patch should be :

        function signature ( $request, $base_string, $consumer_secret, $token_secret )
        {
                $base_string .= '&'.$request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret);
                $md5 = md5($base_string);
                $bin = '';
                
                for ($i = 0; $i < strlen($md5); $i += 2)
                {
                    $bin .= chr(hexdec($md5{$i+1}) + hexdec($md5{$i}) * 16);
                }
                return $request->urlencode(base64_encode($bin));
        }

Regards,

Johann Fradj

Comment by jeffre...@gmail.com, Nov 17, 2009

I am trying to make a postgresql port, how can i test whether my code works? is there any available test suite?

Comment by alexheim...@gmail.com, Nov 24, 2009

Hey guys,

OAuth 1.0a compatibility was not implemented on the server part so I did it myself.

This patch does the following :

- protect OAuth transaction against Man in the middle attack by keeping the callback url associated with the request token. There's no need to pass the callback through the authorize call

- return an oauth_verifier code when authorizing the request token. This oauth_verifier is used when no callback can be used (mobile and desktop application).

Anybody interested in this patch ?

Comment by andrew%a...@gtempaccount.com, Dec 4, 2009

@alexheimburger - If you added 1.0a compatibility, would it be possible to get your patch? Can you post it somewhere?

Thanks, Andrew

Comment by sublim...@gmail.com, Dec 22, 2009

@alexheimburger yep, interested here too

Comment by fehavis...@gmail.com, Dec 27, 2009

How to define MySQL connections if I don't want to use a 1) Create a virtual host and set the DB_DSN VARIABLE to the DSN of your (mysql) database.

? I want to use just simple way of connection.

Comment by fehavis...@gmail.com, Dec 27, 2009

I found it and altered the connection at: the file is at: example/server/core/init.php :-)

Comment by php...@gmail.com, Jan 17, 2010

OMG

if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        // See if the user clicked the 'allow' submit button (or whatever you choose)
        $authorized = array_key_exists('allow', $_POST);

        // Set the request token to be authorized or not authorized
        // When there was a oauth_callback then this will redirect to the consumer
        $server->authorizeFinish($authorized, $user_id);

        // No oauth_callback, show the user the result of the authorization
        // ** your code here **
   }
Comment by kei...@gmail.com, Feb 28, 2010

How anyone is able to understand this documentation is beyond me. Is there any other example documentation available for idiots like me to understand?

Comment by project member profile....@gmail.com, Feb 28, 2010

You might want to take a look at the example server implementation: http://code.google.com/p/oauth-php/source/browse/#svn/trunk/example/server

Comment by psg...@gmail.com, Mar 3, 2010

I'm just as confused as you are, keiron. Where in that example can we find request_token.php, authorize.php and access_token.php?

Comment by project member profile....@gmail.com, Mar 3, 2010

They are just called a bit different, take a look at the www directory and you will be able to find the individual controllers.

Comment by magne...@gmail.com, Mar 24, 2010

Any thoughts on good ways of adding support for xAuth in this library? I was hoping it would be pretty trivial, but I'm not so sure anymore. Any tips?

Comment by nama...@gmail.com, Mar 25, 2010

hi

i am trying to set up a oauth server. everything goes well untill the point i need to authorize my token. i use the twolegged.php client file. and set the url to myoauthserver.local/oauth/authorize. but when i do that i get this message

Exception: exception 'OAuthException2' with message 'Request failed with code 400: Failed OAuth Request: Unknown request token ""' in G:\xampp\xampp\htdocs\oauth\library\OAuthRequester.php:117 Stack trace: #0 G:\xampp\xampp\htdocs\oauth\example\client\twolegged.php(56): OAuthRequester->doRequest() #1 {main}

can somebody help me with that. the only thing that works at the moment is the request of tokens

Comment by psotoul...@gmail.com, Apr 16, 2010

Why the library use $SESSION values in the OAuthServer class? is this a contradiction of the RESTful principies?

Comment by project member profile....@gmail.com, Apr 16, 2010

Hi Psotoulloa,

The OAuth handshake is not about being RESTful. During the authorization a user is asked if he agrees to give the consumer access to his account. For this a page with a form (or buttons) will be shown in the user agent (browser) of the user. The user also needs to be logged on, so it is quite safe to assume that there is a SESSION available at that stage of the OAuth handshake.

- Marc

Comment by psotoul...@gmail.com, Apr 20, 2010

Hi Marc. thanks for your feedback, thats makes sence. Patricio

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

@psotoulloa: besides what profile.url has written, if the problem lies in using SESSION as storage the current SVN version has support for other storage systems.

@magnethy: I don't think xAuth has much to do with this library.

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

How do i control a Out-Of-Band case? I would display a message like: "Close this window and go back to your application." But the Server tries to redirect to http://oob/...?

thx André

Comment by project member brunobg%...@gtempaccount.com, May 7, 2010

@fiedler.andre: see the new OOB section above.

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

Thx, but lets say i´ve set the "osr_application_type" to eighter "mobile application" or "browser", how can i tell the OAuthServer not to redirect if the osr_application_type is "mobile apllication"?

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

Ok, got the problem fixed. See  issue #37  for more details.

Thanks again, André

Comment by jonnyber...@gmail.com, May 17, 2010

I've installed the sample server according to the instructions in "INSTALL" file. Using a consumer client (that works for Twitter, status.net), I'm trying to access this test server but AFAIK fail on getting the access token. It just ends with a empty white screen on the url "oauth/authorize?oauth_token=salkdlkjsdljxxx..." - there is no getting kicked back to a callback - even though I set a callback.

Comment by mapk...@gmail.com, May 24, 2010

I am attempting to authorise a client using code based on the code above.

I am using the MySQL store, but due to reasons I won't go into I need to use a prior initialised store.

The server and request verifier however will always create and initialise a standard mysql datastore as part of their constructors. This prevents you using a pre-initialised mysql datastore (or for that matter, any other datastore) unless I modify the library code to allow this (can do, would prefer not to).

Before I did this I'd like to check whether I was missing something...?

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

no, you can pass the connection:

OAuthStore::instance('MySQL', array(

'conn' => $yourDBConnection
));

Comment by yuenchi....@gmail.com, Jul 7, 2010

> Thx, but lets say i´ve set the "osr_application_type" to eighter "mobile > application" or "browser", how can i tell the OAuthServer not to redirect if > the osr_application_type is "mobile apllication"?

I know this is almost two-month old, the answer, it's an application issue - its responsibility, to provide certain level of filtering for such restriction.

Comment by project member fiedler....@gmail.com, Jul 7, 2010

take a look at $server->authorizeFinish(...)

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

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 vinaykant.sahu, Aug 4, 2010

Hello All,

I have made some changes in this great library and added Oracle store. There is ready Oracle SPs and db schema based on this MySQL store. I would like to share that with you for more Improvement, so please let me know how can I contribute with all of you?

Regards Vinaykant

Comment by vlada.pe...@gmail.com, Aug 5, 2010

In OAuthServer.php I found some errors typo.

line 209

$verififer = null;

should be

$verifier = null;

Great lib. Good work.

Comment by project member brunobg%...@gtempaccount.com, Aug 5, 2010

@vinaykant.sahu Yes, please send us! Open a new issue and post your patch there. I can grant you write access to the SVN if necessary.

@vlada.petrovic: Thanks a lot for the notice, already fixed! But please prefer to open an issue to report bugs next time.

Comment by ebot.t...@gmail.com, Sep 8, 2010

hey i have use the library from here and developed an OAuth service provider with a simple client on kohanaPHP framework, i wish to share with you guys but i got no svn to comit, since i am using windows and i am not use to using SVN. but i will fine a way to host it for others to. i did some modification but you will. any suggestions on how to add an api on the oauth service now will be help to me since i am just learning and wish to share with others

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

@ebot.tabi: please create a new issue and post your code there. I'll add it to the SVN.

Comment by ebot.t...@gmail.com, Sep 9, 2010

@brun ok thanks i will create a new issue and post my codes then

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 vivekris...@gmail.com, Oct 5, 2010

A very useful library!! I am facing a small hiccup! When I run the twolegged.php and try to access hello.php in server, I get this error!

ExceptionRequest? failed with code 401: OAuth Verification Failed: The consumer_key "c76f224ae0ea41eaf76a6d26350e1cdd04caa5ffe" token "0952088aa9b54cae5646dc142ade86a704cab4d96" combination does not exist or is not enabled

What should I be checking to make it work fine?

Comment by enno0815de, Oct 7, 2010

Hi, any new informations about xauth?

Enno

Comment by mconve...@gmail.com, Oct 15, 2010

Hi Guys, thank you for your great work!

I am using your library, I updated your code in order to use the callback stored into the oauth_server_registry table;

In particular I have: 1) modified OAuthStoreSQL.php at getConsumerRequestToken function; my code:

public function getConsumerRequestToken ( $token )
	{
		$rs = $this->query_row_assoc('
				SELECT	ost_token			as token,
						ost_token_secret	as token_secret,
						osr_consumer_key	as consumer_key,
						osr_consumer_secret	as consumer_secret,
						ost_token_type		as token_type,
 						ost_callback_url    as callback_url,
 						osr_application_title as application_title,
 						osr_application_descr as application_descr,
 						osr_application_uri   as application_uri,	
 						osr_callback_uri    as default_callback_uri				
				FROM oauth_server_token
						JOIN oauth_server_registry
						ON ost_osr_id_ref = osr_id
				WHERE ost_token_type = \'request\'
				  AND ost_token      = \'%s\'
				  AND ost_token_ttl  >= NOW()
				', $token);
		
		return $rs;
	}

The modify must be done in your store if you want use my approach

2) I modified the authorizeVerify function in OAuthServer.php in order to check the default callback uri:

			$cb = $this->getParam('oauth_callback', true); 
			if ($cb){
				$this->session->set('verify_oauth_callback', $cb);
			}else if ($rs['default_callback_uri'] != null && $rs['default_callback_uri'] != ''){
					$this->session->set('verify_oauth_callback', $rs['default_callback_uri']);
				} else {
					$this->session->set('verify_oauth_callback', $rs['callback_url']);
				}

In this way people can store a default callback uri and use that.

What do you think about?

Maurizio http://www.maurizioconventi.com

Comment by ikoS...@gmail.com, Oct 21, 2010

Hi, im new using this library. Really great work! im having problems accessing to protected resources in a 3legged consumer-server app (I have Access tokens) ¿Is there a example or a How to? I suposed that doRequest() is the way to do this but cant understand how to use it. Thanks.

Comment by ebot.t...@gmail.com, Nov 22, 2010

Hi guys please has any one implemented rate limiting?

Comment by ChackoNe...@gmail.com, Jan 2, 2011

I am very new to OAuth. I shall describe the use case I want to try, and somebody kindly tell if that is possible, and if so, point to some reference for implementation.

I have a php server side site, running Apache2, which uses the httpasswd for access. Currently every user has an email id and a password (from us). Is it possible, if these users have a gmail id, they can be authenticated using their gmail id instead of using the current site specific password. Of course since everybody may not even eventually have a gmail id, this need to coexist with the current htpassword authentication. That is if a user can be authenticated by either method, access will be granted. It is not a store, there is really no transaction, other than just login for access to members.

Thank you for your help!

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

I am using the Most recent release available for download for Server and have implemented it.

But as Here mentioned in "OOB" section that you will be redirected to http://oob/?oauth_token=xxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxx but its not like that

You will not be redirected as per the implementation from recent build.

So i have made changes to my OAuthServer.php to print the "verifier" in response to OOB calls like PIN: xxxxxx, so that it can be entered to client app/mobile app not supporting browser and still will be able to get access_tokens based on that PIN.

I guesss Twitter and Yahoo may have implemented in that way. So i did it!

cheers, nEosAg

Comment by andrewma...@gmail.com, Feb 1, 2011

@ChackoNeroth?

Please read this: http://code.google.com/googleapps/domain/sso/openid_reference_implementation.html for using Google Single Sign On OpenID API...

Comment by archul...@seqcentral.com, Feb 18, 2011

Here's a quick method to have your server try both 2-legged and 3-legged authentication:

	function _valid_request() {
		// At the start of every request handled by your application you can check if the request contains OAuth authorization information.
		if (OAuthRequestVerifier::requestIsSigned())
		{
			try
			{
				$req = new OAuthRequestVerifier();
				$user_id = $req->verify();
			}
			catch (OAuthException2 $e)
			{
				// The request was signed, but failed 3-legged verification, try 2-legged
				try
				{
					$req = new OAuthRequestVerifier();
					$extended_info = $req->verifyExtended(false);
					$user_id = $extended_info['osr_id']);
				}
				catch (OAuthException2 $e)
				{
					// The request was signed, but failed both 2-legged and 3-legged verification
					header('HTTP/1.1 401 Unauthorized');
					header('WWW-Authenticate: OAuth realm=""');
					header('Content-Type: text/plain; charset=utf8');
		
					echo $e->getMessage();
					exit();
				}
			}
			// If we have an user_id, then login as that user (for this request)
			if ($user_id)
			{
				// **** Add your own code here ****
				return $user_id;
			}
		}
		return FALSE;
	}
Comment by mokachee...@gmail.com, Mar 11, 2011

Any way to turn off the AuthStore?? I'd like to handle this on my own. Awesome library, but I'm running into a roadblock with sql errors and I'd like to store the data in my own table (users).

Comment by lds1...@gmail.com, Apr 19, 2011

please change code in example : catch (OAuthException $e) to catch (OAuthException2 $e)

Comment by jzel...@gmail.com, Jul 7, 2011

Okay, as I understand this, whenever a client/consumer sends a user to my API to register, it creates a unique entry that holds both client and user. But I want to set up my API the way Twitter does: namely, a dev has to register their client/consumer first, are given an API key, and then a unique token is generated for each user who uses their client.

Is there an easy way to do this, or am I going to have to rewrite a bunch of SQL code here to make this work?

Comment by kwsamara...@gmail.com, Jul 27, 2011

Hi

I m using this library for a REST based API authentication. I have a problem about hello.php. It initializes OAuthServer without any parameters. But with "$params" array it reads oauth parameters. So dont we need to pass request header parameters to OAuthserver? Am I wrong?

Thanks kasun

Comment by luisbati...@domdigital.com, Aug 9, 2011

Hi all,

I have problems to validate the signature.

The script pass the request_token and authorize step, but fail on access_token.

I put here the result when I call: $request = new OAuthRequester($access_url, "GET", $param);

OAuthRequester Object
(
    [files:protected] => 
    [request:protected] => 
    [store:protected] => OAuthStore2Leg Object
        (
            [consumer_key:protected] => 6d6f2ef888d18e54048abd01f06568d204e3fce3d
            [consumer_secret:protected] => 1b113c90815192e504ceef86aefc9394
            [signature_method:protected] => Array
                (
                    [0] => HMAC-SHA1
                )

            [token_type:protected] => 
        )

    [usr_id:protected] => 0
    [signed:OAuthRequestSigner:private] => 
    [realm:protected] => 
    [param:protected] => Array
        (
            [a] => access_token
            [oauth_token] => 4cf297bb223e8b951541550f8876496d04e40f64e
            [oauth_verifier] => d1ee59e20a
        )

    [uri_parts:protected] => Array
        (
            [scheme] => http
            [host] => localhost
            [path] => /oauthtest/oauth.php
            [query] => a=access_token
            [port] => 80
            [user] => 
            [pass] => 
            [fragment] => 
        )

    [uri:protected] => http://localhost/oauthtest/oauth.php?a=access_token
    [headers:protected] => Array
        (
            [Accept] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
            [Accept-Charset] => ISO-8859-1,utf-8;q=0.7,*;q=0.7
            [Accept-Encoding] => gzip, deflate
            [Accept-Language] => pt-pt,pt;q=0.8,en;q=0.5,en-us;q=0.3
            [Connection] => keep-alive
            [Cookie] => PHPSESSID=k4p2902tv0ksatltkrtbb98tf0
            [Host] => localhost
            [User-Agent] => Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0
        )

    [method:protected] => GET
    [body:protected] => 
)

AND the error I get:

Error : Request failed with code 401: OAuth Verification Failed: Verification of signature failed (signature base string was "GET&http%3A%2F%2Flocalhost%2Foauthtest%2Foauth.php&a%3Daccess_token%26oauth_consumer_key%3D6d6f2ef888d18e54048abd01f06568d204e3fce3d%26oauth_nonce%3D4e40f64eef9c8%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1312880206%26oauth_token%3D4cf297bb223e8b951541550f8876496d04e40f64e%26oauth_verifier%3Dd1ee59e20a%26oauth_version%3D1.0"). 
with Array ( 
  [0] => 1b113c90815192e504ceef86aefc9394 
  [1] => 7c9e7b65f1f344c001f7063afc487a18 
  [2] => request 
) 

Can anyone help me resolve this issue?

Other situation, I test the script on my computer, a Windows+Apache+MySQL+PHP enviroment, but I will put the script on a Windows Server+IIS7+MySQL+PHP, this script run on this configuration?

Best Regards, LB

Comment by jimbomor...@gmail.com, Sep 1, 2011

Including user_id on the access_token response

We've be playing with this great code but one thing we wanted to add was the user_id to the access_token response ( like twitter does for example ) because you need to know against which user account to store the credentials. Unless the API you're dealing with provides a simple url that allows you to fetch the 'authenticated users' credentials you're a bit stuck - either way that's possibly a superflous request.

Our solution is as follows and posted here for anyone else having the same problem.

In the OAuthServer.php class; the accessToken() function calls the verifer();. The response to that call is the user_id... but it's discarded. Therefore edit the first line of code to read:

$user_id = $this->verify('request');

Then further down in the method, after we've compiled all the other bits of the return string, simply add the following:

if (!empty($user_id)){
	$result .= '&user_id='.$this->urlencode($user_id);
}

Job done.

Very interested to know if anyone says it's bad behaviour to provide this information at this juncture. As I say twitter does it so that would make it pretty common behaviour.

Hope this helps someone.

Jimbo

Comment by seifert....@gmail.com, Sep 22, 2011

Thats weird, I've had/got the same error message as luisbati...@domdigital.com from above.

What "solved" the issue for me was to give the arguments to the arguments to the url in the same order as reported by the "signature base string" in the error message. That error message had the first two arguments (my custom arguments) in the url swapped.

I did the same in the actual request and the signature error was gone. Is there anything ordered in the list of arguments? Any way to avoid that?

Thanks,

Thomas

Comment by seifert....@gmail.com, Sep 22, 2011

Ok, maybe I found it. getNormalizedParams has a line: ksort($params);

which, well, sorts the params by key. So the signature for checking is generated on ordered params in the url while the signature delivered from the app is generated on the order the params are given in => mismatch.

Therefore the question is: Is that ksort in any way needed or required?

Thanks,

Thomas

Comment by jasonpha...@gmail.com, Oct 16, 2011

Please help. I got a message from login screen "You must install php5-oauth to use this class"??? though I am using PHP 5.2 (goDaddy host). What am I missing and how to fix this, Appreciate your help. Thanks Jason.

Comment by techie...@gmail.com, Nov 24, 2011

How can i install this on my server.I dont know how to set env variable there.

Comment by 35812...@qq.com, Dec 30, 2011

$user_id = 3; // Request parameters are oauth_token, consumer_key and usr_id. $consumer_key = "45fd7a0c11640a04859ccc3d5ec0ae2004efd7c78"; $oauth_token = $GET['oauth_token']; try {

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

Fatal error: Uncaught exception 'OAuthException2' with message 'The server "http://auth.service.com/access_token.php" did not return the oauth_token or the oauth_token_secret' in D:\AppServ?\www\demo\oauth-php\library\OAuthRequester.php:281 Stack trace: #0 D:\AppServ?\www\demo\test.php(14): OAuthRequester::requestAccessToken('45fd7a0c11640a0...', '595e0ee21c8aa09...', 3, 'POST', Array) #1 {main} thrown in D:\AppServ?\www\demo\oauth-php\library\OAuthRequester.php on line 281

access_token.php <?php include_once 'oauth-php/library/OAuthServer.php'; $server = new OAuthServer(); $rs = $server->accessToken(); ?>

server access_token.php error why?

Comment by vansteenlandt.jan@gmail.com, Feb 18, 2012

Hi guys,

I don't quite get the concept of the user_id (partly due to confusing comments in the example code).

So I understand the fact that a user gives permission to consumers to access something. As I understand the user_id has to be passed to register a consumer ( so a user has to be logged in, in order to allow a consumer to register with the OAuth server?? ) Then when u authorize an unauth. request token again u have to pass along the user_id... So is this something you store per user in your server ( i.e. John Doe = user_id 6; Jane Doe = user_id 88 ) I read somewhere this should be stored in session so I think that's just to remember that john doe has logged in and you store his user_id in the session....?

A little explanation or confirmation would help me sooo much !!!

Thx in advance, and nice framework !!

Jan

Comment by r.cap...@mademediacorp.com, Mar 6, 2012

Hey guys,

is there any sample code on how to get this server to work with the 2-legged version of the Oauth Store? The one that's included with the library just stores the consumer token and secret. How does one use this?

Thanks!

Comment by aa...@cogilent.com, Apr 1, 2012

Hello, i am confused with it. will anyone tell me from where i start? i need to implement the three legged for Single Sign On. please help, Thanks


Sign in to add a comment
Powered by Google Project Hosting