PHP Classes

Google OAuth Offline Access and to Other API with Limited Lifetime Refresh Tokens After their Expiry - PHP OAuth Library package blog

Recommend this page to a friend!
  All package blogs All package blogs   PHP OAuth Library PHP OAuth Library   Blog PHP OAuth Library package blog   RSS 1.0 feed RSS 2.0 feed   Blog Google OAuth Offline ...  
  Post a comment Post a comment   See comments See comments (16)   Trackbacks (0)  

Author:

Viewers: 628

Last month viewers: 197

Package: PHP OAuth Library

Some applications require access to APIs on behalf of the user even when the user is not present, i.e. offline access.

OAuth is a protocol that allows applications to obtain a token to access an API when the user is not present but when the tokens expire they need to be renewed.

Some APIs like Google and Box.net support automatic renewal of expired tokens.

Read this article to learn how to use this OAuth client class to perform offline access to an API storing tokens in a database and how to have expired tokens automatically renewed.




Loaded Article

Contents

Using OAuth Tokens to Access APIs Without the User Presence

Setting up the Tokens for Offline Access

Retrieving Access Tokens from a Database

Retrieving Access Tokens from a MySQL database

Offline API access

Automatic Renewal of Expired Tokens

Conclusion

Using OAuth Tokens to Access APIs Without the User Presence

PHP + OAuth released under the Creative Commons Attribution ShareAlike 3.0 licenseOAuth is a protocol that was thought to grant external applications the permission to call Web site API functions on behalf of an user.

It can be used for instance to get details of the user account like his name or even email address, manipulate personal user information like for instance uploading user pictures, execute tasks as if it was the user executing them like sending scheduled posts to Facebook or Twitter, etc..

The way the OAuth protocol works, the user must be present online to grant permission to an external application so it can access the API on his behalf later.

Tokens are secret values generated by the API server that grants the access permissions. These tokens must be used by the external applications to perform API calls, so the server knows on behalf of which user the API is being called.

From then on the applications can perform API calls at will. The user is no longer required to be present while the tokens are valid. When the user is not present, this is called API offline access.

Offline access may be important for some applications that need to automate tasks that will be executed when the user is not present. That is for instance the case of applications that send posts to Twitter or Facebook at a given scheduled time.

Setting up the Tokens for Offline Access

As it was explained in a previous article, the usual way to process the OAuth protocol interactions using this class is to first call the Initialize function to setup the class object.

Then call the Process function to make the class handle the interactions between your application and the OAuth server to obtain the token values.

The access_token variable contains the main token value. For OAuth 1 servers, a secondary value is stored in the access_token_secret variable.

When you are done with the class, you need to call the Finalize function to cleanup any resources the class used during the process.

The calls to the server API must be done using the CallAPI function. It must be called only between the Initialize and Finalize calls.

The CallAPI function must be called only when the token values are obtained successfully. If the token values are being retrieved for the first time using the Process function, obviously the CallAPI function may only be called after a successful call to the Process function.

From then on, your application may perform as many calls to the API as necessary, but you no longer need to call the Process function before calling CallAPI.

You just need to set the tokens first before any call to CallAPI. You can do this using two methods. The first method is to set the access_token and access_token_secret variables directly.

Retrieving Access Tokens from a Database

An alternative method to retrieve OAuth tokens consists in creating a sub-class and implement the functions GetAccessToken and StoreAccessToken functions to retrieve the token values from a database.

This is a more complicated method but it is recommended for offline access to the API because by default the OAuth client base class stores the retrieved tokens in session variables.

Session variables can only be used when the user is accessing a PHP based Web page. So if your application needs to get the previously retrieved tokens to make an offline access to the API, the default implementation of the GetAccessToken and StoreAccessToken functions is not appropriate.

This package provides a special sub-class named database_oauth_client_class to store and retrieve tokens automatically in a database. This sub-class alters the way tokens are stored and retrieved so a database is used instead of sessions.

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.

Feel free to post a comment to this article if you have questions not answered by this article or you would like to present other use cases not yet handled by the class.




You need to be a registered user or login to post a comment

1,611,040 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:



Comments:

5. Offline Access to Google by Retrieving Access Tokens from a file - Eric Lu (2015-10-22 04:35)
Use a file to retrieve and store instead of database... - 7 replies
Read the whole comment and replies

4. Google contact offline - shirish (2015-07-13 18:07)
Google contact offline... - 2 replies
Read the whole comment and replies

3. Re: PHP OAuth class Post to user's LinkedIn Account - thirupathi reddy (2014-12-12 05:48)
2... - 1 reply
Read the whole comment and replies

2. Problem with refresh token - bolandfranck (2013-05-25 11:31)
Problem with refresh token... - 1 reply
Read the whole comment and replies

1. Useful - Guttemberg Alves (2013-04-23 21:08)
Nice... - 0 replies
Read the whole comment and replies



  Post a comment Post a comment   See comments See comments (16)   Trackbacks (0)  
  All package blogs All package blogs   PHP OAuth Library PHP OAuth Library   Blog PHP OAuth Library package blog   RSS 1.0 feed RSS 2.0 feed   Blog Google OAuth Offline ...