Offline Access to Google and other OAuth based API – PHP OAuth API – Part 2

Sharing is caring!

Retrieving Access Tokens from a MySQL database

The database_oauth_client_class is just a generic SQL database storage class. It really does not execute SQL queries because that depends on the type of database you want to store your tokens. A more specialized sub-class is necessary to execute the SQL queries to a specific type of database.

This package also comes with another sub-class named mysqli_oauth_client_class that is specialized in executing the SQL queries to a MySQL database using the mysqli extension. If you use a different type of database, you can use this sub-class as model to execute SQL queries using the appropriate PHP extension.

Lets see how you can make this work in practice to make the tokens be stored and retrieved in a MySQL database. The first thing you need to do is to setup your database schema have a table named oauth_session for storing the tokens. This table should be created in your application database.

You may install the table executing the following SQL statements.
DROP TABLE IF EXISTS `oauth_session`;
CREATE TABLE `oauth_session` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`session` char(32) NOT NULL DEFAULT ”,
`state` char(32) NOT NULL DEFAULT ”,
`access_token` mediumtext NOT NULL,
`expiry` datetime DEFAULT NULL,
`type` char(12) NOT NULL DEFAULT ”,
`server` char(12) NOT NULL DEFAULT ”,
`creation` datetime NOT NULL DEFAULT ‘2000-01-01 00:00:00’,
`access_token_secret` mediumtext NOT NULL,
`authorized` char(1) DEFAULT NULL,
`user` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `social_oauth_session_index` (`session`,`server`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Some fields are not really mandatory for most applications but the database_oauth_client_class assumes they are there, so do not change this table schema. This SQL definition is provided with this package as a separate file named oauth.sql.

The process to actually retrieve the access token values to be stored in a database is the same. The main difference is that you will use the mysqli_oauth_client_class instead of the base class.

There are a few minor differences. The most obvious is that you need to define the database connection options. This done using the database class variable. This is an array with several entries for the options.
$client->database = array(
‘host’=>’localhost’,
‘user’=>’database user here’,
‘password’=>’database password here’,
‘name’=>’database name here’,
‘port’=>3328,
‘socket’=>”
);

Since you want to access the API when the user is not present, some OAuth servers require that you use a specific authorization URL to request offline access. The oauth_client_class is aware of differences in the authorization URL for some types of servers. Just set the class offline variable, so the class uses the appropriate URL.
$client->offline = true;

Another important detail is that you need to associate the obtained OAuth tokens with a user in your application site.

This is important because when later your application will perform offline API access on behalf of that user, your application needs to locate the respective access token values stored in your database using the respective user id.

The database_oauth_client_class provides a function named SetUser for this purpose. It takes the user id value as parameter. It should be called once your authorization script is able to associate the user in your application with the just obtained OAuth tokens.

Your authorization script code may look like this:
if(($success = $client->Process()))
{
if(strlen($client->authorization_error))
{
$client->error = $client->authorization_error;
$success = false;
}
elseif(strlen($client->access_token))
{
$current_user_id = 1;
$success = $client->SetUser($current_user_id);
}
}

Take a look at the mysqli_login_with_google.php example script to see a practical example of how to use these settings.

Offline API access

Now that you have made your application store the access token values in a database, your application is ready to perform offline API accesses on behalf of a user that is not present.

The process of making API calls is the same using the CallAPI function. As mentioned above, you need to call this function between calls to the Initialize and Finalize functions.

You no longer need to call the Process function because that is only necessary to establish the OAuth interaction with the server to obtain the user permission to access the API. Since you already have obtained the access tokens and they are stored in your database, calling the Process function is not needed for offline access.

The database_oauth_client_class is able to retrieve the access token values when the CallAPI function is called. The only thing it needs is the id of the user on behalf of whom your application will access the API. You need to set the user class variable for that purpose.
$some_user_id = 1
$client->user = $some_user_id;

Take a look at the mysqli_offline_access_to_google.php script for a complete example of code for accessing the Google API offline.

Automatic Renewal of Expired Tokens

When an access token expires, you need to replace the token by a new one. With most API the only way to do it is to prompt the user and request to go through the authorization process again.

This is not ideal because you need to communicate with the user and ask him to come to your site again. Until that happens you cannot access the API again using the expired token values. Unfortunately you need to anticipate this case in your application.

Fortunately some API based on OAuth 2 provide means to refresh tokens automatically. This is the case for instance of Google and Box.net. They support refresh tokens, which are additional tokens that can be used to obtain new access tokens when these expire.

The oauth_client class supports exchanging refresh tokens automatically during calls to the CallAPI function. So, as long as the server supports refresh tokens, you do not need to be concerned with the token refresh procedure because the class takes care of that for your application.

The only thing you need to do is to set the offline variable to true in the code of your application that executes the authorization procedure, as explained above.

Conclusion

The OAuth protocol may become a bit complicated when you try to handle more complex use cases like accessing an API when the user is not present and the access token needs to be renewed because it expired.

Fortunately this OAuth class was thought to deal with all those use cases minimizing the complexity of your application.

Source From: http://www.phpclasses.org

Leave a Reply

Your email address will not be published. Required fields are marked *

Got Project on mind? Let's ConnectContact Us

Secured By miniOrange