Version: @(#) $Id: oauth_client.php,v 1.182 2022/05/10 01:51:03 mlemos Exp $
OAuth client
Manuel Lemos (mlemos-at-acm.org)
@(#) $Id: oauth_client.php,v 1.182 2022/05/10 01:51:03 mlemos Exp $
This class serves two main purposes:
1) Implement the OAuth protocol to retrieve a token from a server to authorize the access to an API on behalf of the current user.
2) Perform calls to a Web services API using a token previously obtained using this class or a token provided some other way by the Web services provider.
Regardless of your purposes, you always need to start calling the class Initialize function after initializing setup variables. After you are done with the class, always call the Finalize function at the end.
This class supports either OAuth protocol versions 1.0, 1.0a and 2.0. It abstracts the differences between these protocol versions, so the class usage is the same independently of the OAuth version of the server.
The class also provides built-in support to several popular OAuth servers, so you do not have to manually configure all the details to access those servers. Just set the server variable to configure the class to access one of the built-in supported servers.
If you need to access one type of server that is not yet directly supported by the class, you need to configure it explicitly setting the variables: oauth_version, url_parameters, authorization_header, request_token_url, dialog_url, reauthenticate_dialog_url, pin_dialog_url, offline_dialog_url, append_state_to_redirect_uri and access_token_url.
Before proceeding to the actual OAuth authorization process, you need to have registered your application with the OAuth server. The registration provides you values to set the variables client_id and client_secret. Some servers also provide an additional value to set the api_key variable.
You also need to set the variables redirect_uri and scope before calling the Process function to make the class perform the necessary interactions with the OAuth server.
The OAuth protocol involves multiple steps that include redirection to the OAuth server. There it asks permission to the current user to grant your application access to APIs on his/her behalf. When there is a redirection, the class will set the exit variable to 1. Then your script should exit immediately without outputting anything.
When the OAuth access token is successfully obtained, the following variables are set by the class with the obtained values: access_token, access_token_secret, access_token_expiry, access_token_type. You may want to store these values to use them later when calling the server APIs.
If there was a problem during OAuth authorization process, check the variable authorization_error to determine the reason.
Once you get the access token, you can call the server APIs using the CallAPI function. Check the access_token_error variable to determine if there was an error when trying to to call the API.
If for some reason the user has revoked the access to your application, you need to ask the user to authorize your application again. First you may need to call the function ResetAccessToken to reset the value of the access token that may be cached in session variables.
string
''
Store the message that is returned when an error occurs.
Check this variable to understand what happened when a call to any of the class functions has failed.
This class uses cumulative error handling. This means that if one class functions that may fail is called and this variable was already set to an error message due to a failure in a previous call to the same or other function, the function will also fail and does not do anything.
This allows programs using this class to safely call several functions that may fail and only check the failure condition after the last function call.
Just set this variable to an empty string to clear the error condition.
bool
0
Control whether debug output is enabled
Set this variable to 1 if you need to check what is going on during calls to the class. When enabled, the debug output goes either to the variable debug_output and the PHP error log.
bool
0
Control whether the dialog with the remote Web server should also be logged.
Set this variable to 1 if you want to inspect the data exchange with the OAuth server.
string
''
Name of the file to store log messages
Set this variable to the path of a file to which log messages will be appended instead of sending to PHP error log when the debug variable is set to 1.
bool
0
Determine if the current script should be exited.
Check this variable after calling the Process function and exit your script immediately if the variable is set to 1.
string
''
Capture the debug output generated by the class
Inspect this variable if you need to see what happened during the class function calls.
string
'OAuth client: '
Mark the lines of the debug output to identify actions performed by this class.
Change this variable if you prefer the debug output lines to be prefixed with a different text.
string
''
Identify the type of OAuth server to access.
The class provides built-in support to several types of OAuth servers. This means that the class can automatically initialize several configuration variables just by setting this server variable.
Currently it supports the following servers: '37Signals', 'Amazon', 'AOL', 'Bitbucket', 'Bitly', 'Box', 'Buffer', 'CharterSpectrum', 'CharterSpectrumQA' (CharterSpectrum Quality Assurance), 'Copy', 'Dailymotion', 'Discogs', 'Disqus', 'Dropbox' (Dropbox with OAuth 1.0), 'Dropbox2' (Dropbox with OAuth 2.0), 'Etsy', 'Eventful', 'Facebook', 'Fitbit', 'Flickr', 'Foursquare', 'Garmin', 'github', 'Google', 'Google1' (Google with OAuth 1.0), 'iHealth', 'iHealthSandbox', 'imgur', 'Infusionsoft', 'Instagram', 'Intuit', 'Jawbone', 'LinkedIn', 'LinkedIn2' (LinkedIn with OAuth 2.0), 'mail.ru', 'MailChimp', 'Mavenlink', 'Meetup', 'Microsoft', 'Misfit', 'oDesk', 'Odnoklassniki', 'Paypal', 'PaypalApplication', 'Pinterest', 'Pipedrive', 'Polar', 'Quire', 'Rdio', 'Reddit', 'RunKeeper', 'Salesforce', 'Scoop.it', 'StockTwits', 'SurveyMonkey', 'TeamViewer', 'Tumblr', 'Twitter', 'Vimeo', 'VK', 'Withings', 'Wordpress', 'Xero', 'XING', 'Yahoo', 'Yahoo2', 'Yammer' and 'Yandex'. Please contact the author if you would like to ask to add built-in support for other types of OAuth servers.
If you want to access other types of OAuth servers that are not yet supported, set this variable to an empty string and configure other variables with values specific to those servers.
string
'oauth_configuration.json'
Specify the path of the configuration file that defines the properties of additional OAuth server types.
Change the path in this variable if you are accessing a type of server without support built-in the class and you need to put the configuration file path in a different directory.
string
''
URL of the OAuth server to request the initial token for OAuth 1.0 and 1.0a servers.
Set this variable to the OAuth request token URL when you are not accessing one of the built-in supported OAuth servers.
For OAuth 1.0 and 1.0a servers, the request token URL can have certain marks that will act as template placeholders which will be replaced with given values before requesting the authorization token. Currently it supports the following placeholder marks:
{SCOPE} - scope of the requested permissions to the granted by the OAuth server with the user permissions
string
''
URL of the OAuth server to redirect the browser so the user can grant access to your application.
Set this variable to the OAuth request token URL when you are not accessing one of the built-in supported OAuth servers.
For OAuth 1.0a servers that return the login dialog URL automatically, set this variable to 'automatic'
For OAuth 1.0a servers that support 2 legged authentication set this variable to '2legged'
For certain servers, the dialog URL can have certain marks that will act as template placeholders which will be replaced with values defined before redirecting the users browser. Currently it supports the following placeholder marks:
{REDIRECT_URI} - URL to redirect when returning from the OAuth server authorization page
{CLIENT_ID} - client application identifier registered at the server
{SCOPE} - scope of the requested permissions to the granted by the OAuth server with the user permissions
{STATE} - identifier of the OAuth session state
{API_KEY} - API key to access the server
{REALM} - realm name for OpenID Connect
{NONCE} - unique identifier to made all redirects be unique for OpenID Connect
string
''
URL of the OAuth server to redirect the browser so the user can grant access to your application.
Set this variable when forcing the user to authenticate again and the format of the of the authorization dialog page URL is different than the one set to the dialog_url variable.
string
''
URL of the OAuth server to redirect the browser so the user can grant access to your application.
Set this variable when using the pin based authorization and the format of the of the authorization dialog page URL is different than the one set to the dialog_url variable.
string
''
URL of the OAuth server to redirect the browser so the user can grant access to your application when offline access is requested.
Set this variable to the OAuth request token URL when you are not accessing one of the built-in supported OAuth servers and the OAuth server supports offline access.
It should have the same format as the dialog_url variable.
string
''
Value of the pin code for pin based authorization.
Set this value to the pin informed by the user when implementing the pin based authorization.
Make sure the redirect_uri variable is set to 'oob'.
string
''
Pass the OAuth session state in a variable with a different name to work around implementation bugs of certain OAuth servers
Set this variable when you are not accessing one of the built-in supported OAuth servers if the OAuth server has a bug that makes it not pass back the OAuth state identifier in a request variable named state.
string
''
OAuth server URL that will return the access token URL.
Set this variable to the OAuth access token URL when you are not accessing one of the built-in supported OAuth servers.
string
''
OAuth server URL that will revoke a previously obtain token.
Set this variable to the OAuth revoke token URL when you are not accessing one of the built-in supported OAuth servers.
string
'2.0'
Version of the protocol version supported by the OAuth server.
Set this variable to the OAuth server protocol version when you are not accessing one of the built-in supported OAuth servers.
bool
0
Determine if the API call parameters should be moved to the call URL.
Set this variable to 1 if the API you need to call requires that the call parameters always be passed via the API URL.
bool
1
Determine if the OAuth parameters should be passed via HTTP Authorization request header.
Set this variable to 1 if the OAuth server requires that the OAuth parameters be passed using the HTTP Authorization instead of the request URI parameters.
string
'GET'
Define the HTTP method that should be used to request tokens from the server.
Set this variable to 'POST' if the OAuth server does not support requesting tokens using the HTTP GET method.
string
'HMAC-SHA1'
Define the method to generate the signature for API request parameters values.
Currently it supports 'PLAINTEXT' and 'HMAC-SHA1'.
string
''
URL of the current script page that is calling this class
Set this variable to the current script page URL before proceeding the OAuth authorization process.
For pin based authorization, set this variable to 'oob'.
string
''
Identifier of your application registered with the OAuth server
Set this variable to the application identifier that is provided by the OAuth server when you register the application.
string
''
Secret value assigned to your application when it is registered with the OAuth server.
Set this variable to the application secret that is provided by the OAuth server when you register the application.
string
''
Identifier of your API key provided by the OAuth server
Set this variable to the API key if the OAuth server requires one.
bool
0
Option to determine if the access token should be retrieved using the API key value instead of the client secret.
Set this variable to 1 if the OAuth server requires that the client secret be set to the API key when retrieving the OAuth token.
string
''
Permissions that your application needs to call the OAuth server APIs
Check the documentation of the APIs that your application needs to call to set this variable with the identifiers of the permissions that the user needs to grant to your application.
string
''
Realm of authorization for OpenID Connect
Set this variable to the realm value when using OpenID Connect.
bool
0
Specify whether it will be necessary to call the API when the user is not present and the server supports renewing expired access tokens using refresh tokens.
Set this variable to 1 if the server supports renewing expired tokens automatically when the user is not present.
bool
0
Specify whether it will be necessary to force the user to authenticate again even after the user has already authorized the application before.
Set this variable to 1 if you want to force the user to authenticate again.
string
''
Access token obtained from the OAuth server
Check this variable to get the obtained access token upon successful OAuth authorization.
string
''
Access token secret obtained from the OAuth server
If the OAuth protocol version is 1.0 or 1.0a, check this variable to get the obtained access token secret upon successful OAuth authorization.
string
''
Timestamp of the expiry of the access token obtained from the OAuth server.
Check this variable to get the obtained access token expiry time upon successful OAuth authorization. If this variable is empty, that means no expiry time was set.
string
''
Type of access token obtained from the OAuth server.
Check this variable to get the obtained access token type upon successful OAuth authorization.
string
''
Type of access token to be assumed when the OAuth server does not specify an access token type.
Set this variable if the server requires a certain type of access token to be used but it does not specify a token type when the access token is returned.
string
''
Content type to be assumed when retrieving the response to a request to retrieve the access token.
Set this variable only if the server does not return the correct content type for the access token request response.
string
''
Name of the access token parameter to be passed in API call requests.
Set this variable to a non-empty string to override the default name for the access token parameter which is 'oauth_token' of OAuth 1 and 'access_token' for OAuth 2.
array
The original response for the access token request
Check this variable if the OAuth server returns custom parameters in the request to obtain the access token.
bool
0
Option to determine if the original response for the access token request should be stored in the access_token_response variable.
Set this variable to 1 if the OAuth server returns custom parameters in the request to obtain the access token that may be needed in subsequent API calls.
string
''
Option to determine if the requests to obtain a new access token should use authentication to pass the application client ID and secret.
Set this variable to 'basic' if the OAuth server requires that the client ID and secret be passed using HTTP basic authentication headers when retrieving a new token. Set this variable to 'none' to avoid that the Authorization header be set in the request to get the access token.
string
''
Option to determine if the content type value that should be sent to the OAuth server when it requests the access token.
Set this variable to a specific content type if the OAuth server requires that the 'Accept' header has a specific value.
string
''
Option to determine if the requests to refresh an expired access token should use authentication to pass the application client ID and secret.
Leave this value with an empty string to make it use the same as the access_token_authentication variable. Set this variable to 'none' to avoid that the Authorization header be set in the request to get the refresh token.
string
''
Refresh token obtained from the OAuth server
Check this variable to get the obtained refresh token upon successful OAuth authorization.
string
''
Error message returned when a call to the API fails.
Check this variable to determine if there was an error while calling the Web services API when using the CallAPI function.
string
''
Error message returned when it was not possible to obtain an OAuth access token
Check this variable to determine if there was an error while trying to obtain the OAuth access token.
object
The id_token value from OAuth servers compatible with OpenID Connect.
Check this variable if the OAuth server returns id_token values.
int
0
HTTP response status returned by the server when calling an API
Check this variable after calling the CallAPI function if the API calls and you need to process the error depending the response status. 200 means no error. 0 means the server response was not retrieved.
int
0
HTTP response headers returned by the server when calling an API
Check this variable after calling the CallAPI function if the API calls and you need to process the error depending the response headers.
string
''
Define the user name to obtain authorization using a password.
Set this variable to the user name of the account to authorize instead of going through the interactive user authorization process.
string
''
Define the user name to obtain authorization using a password.
Set this variable to the user password of the account to authorize instead of going through the interactive user authorization process.
string
'authorization_code'
Define the type of grant to obtain the OAuth 2 access token.
Change this variable to 'client_credentials' to obtain application only access token.
Change this variable to 'password' to obtain an access token on behalf of an user with a given username and password specified by the oauth_username and oauth_password variables respectively.
In this case the user does not need to be present, so the class will not redirect the user to the authorization dialog page.
array
array()
Define additional arguments to configure the HTTP requests.
Set this associative array with argument values that you need to set options of the HTTP requests sent to the OAuth server and API URLs.
Check the documentation of the HTTP client class for more information on the available arguments that can be configured using this option.
Redirect(
Redirect the user browser to a given page.
This function is meant to be only be called from inside the class. By default it issues HTTP 302 response status and sets the redirection location to a given URL. Sub-classes may override this function to implement a different way to redirect the user browser.
url - String with the full URL of the page to redirect.
bool StoreAccessToken(
Store the values of the access token when it is succefully retrieved from the OAuth server.
This function is meant to be only be called from inside the class. By default it stores access tokens in a session variable named 'OAUTH_ACCESS_TOKEN'.
Actual implementations should create a sub-class and override this function to make the access token values be stored in other types of containers, like for instance databases.
access_token - Associative array with properties of the access token. The array may have set the following properties:
'value': string value of the access token
'authorized': boolean value that determines if the access token was obtained successfully
'expiry': (optional) timestamp in ISO format relative to UTC time zone of the access token expiry time
'type': (optional) type of OAuth token that may determine how it should be used when sending API call requests.
'refresh': (optional) token that some servers may set to allowing refreshing access tokens when they expire.
This function should return 1 if the access token was stored successfully.
bool GetAccessToken(
Retrieve the OAuth access token if it was already previously stored by the StoreAccessToken function.
This function is meant to be only be called from inside the class. By default it retrieves access tokens stored in a session variable named 'OAUTH_ACCESS_TOKEN'.
Actual implementations should create a sub-class and override this function to retrieve the access token values from other types of containers, like for instance databases.
access_token - Return the properties of the access token in an associative array. If the access token was not yet stored, it returns an empty array. Otherwise, the properties it may return are the same that may be passed to the StoreAccessToken.
This function should return 1 if the access token was retrieved successfully.
bool ResetAccessToken()
Reset the access token to a state back when the user has not yet authorized the access to the OAuth server API.
Call this function if for some reason the token to access the API was revoked and you need to ask the user to authorize the access again.
By default the class stores and retrieves access tokens in a session variable named 'OAUTH_ACCESS_TOKEN'.
This function must be called when the user is accessing your site pages, so it can reset the information stored in session variables that cache the state of a previously retrieved access token.
Actual implementations should create a sub-class and override this function to reset the access token state when it is stored in other types of containers, like for instance databases.
This function should return 1 if the access token was resetted successfully.
bool CallAPI(
Send a HTTP request to the Web services API using a previously obtained authorization token via OAuth.
This function can be used to call an API after having previously obtained an access token through the OAuth protocol using the Process function, or by directly setting the variables access_token, as well as access_token_secret in case of using OAuth 1.0 or 1.0a services.
The response_status variable returns the HTTP response status of the request.
The response_headers variable returns the HTTP the request response headers.
url - URL of the API where the HTTP request will be sent.
method - HTTP method that will be used to send the request. It can be 'GET', 'POST', 'DELETE', 'PUT', etc..
parameters - Associative array with the names and values of the API call request parameters.
options - Associative array with additional options to configure the request. Currently it supports the following options:
'2Legged': boolean option that determines if the API request should be 2 legged. The default value is 0.
'Accept': content type value of the Accept HTTP header to be sent in the API call HTTP request. Some APIs require that a certain value be sent to specify which version of the API is being called. The default value is '*/*'.
'ConvertObjects': boolean option that determines if objects should be converted into arrays when the response is returned in JSON format. The default value is 0.
'DecodeXMLResponse': name of the method to decode XML responses. Currently only 'simplexml' is supported. It makes a XML response be parsed and returned as a SimpleXMLElement object.
'FailOnAccessError': boolean option that determines if this functions should fail when the server response status is not between 200 and 299. The default value is 0.
'Files': associative array with details of the parameters that must be passed as file uploads. The array indexes must have the same name of the parameters to be sent as files. The respective array entry values must also be associative arrays with the parameters for each file. Currently it supports the following parameters:
- Type - defines how the parameter value should be treated. It can be 'FileName' if the parameter value is is the name of a local file to be uploaded. It may also be 'Data' if the parameter value is the actual data of the file to be uploaded.
Default: 'FileName'
- FileName - defines a custom file name for the file to be uploaded.
Default: none
- ContentType - MIME value of the content type of the file. It can be 'automatic/name' if the content type should be determine from the file name extension.
Default: 'automatic/name'
'PostValuesInURI': boolean option to determine that a POST request should pass the request values in the URI. The default value is 0.
'FollowRedirection': limit number of times that HTTP response redirects will be followed. If it is set to 0, redirection responses fail in error. The default value is 0.
'RequestBody': request body data of a custom type. The 'RequestContentType' option must be specified, so the 'RequestBody' option is considered.
'RequestContentType': content type that should be used to send the request values. It can be either 'application/x-www-form-urlencoded' for sending values like from Web forms, or 'application/json' for sending the values encoded in JSON format. Other types are accepted if the 'RequestBody' option is specified. The default value is 'application/x-www-form-urlencoded'.
'RequestHeaders': associative array of custom headers to be sent with the API call. These headers override any values set by the class when sending the API call HTTP request.
'Resource': string with a label that will be used in the error messages and debug log entries to identify what operation the request is performing. The default value is 'API call'.
'ResponseContentType': content type that should be considered when decoding the API request response. This overrides the Content-Type header returned by the server. If the content type is 'application/x-www-form-urlencoded' the function will parse the data returning an array of key-value pairs. If the content type is 'application/json' the response will be decode as a JSON-encoded data type. Other content type values will make the function return the original response value as it was returned from the server. The default value for this option is to use what the server returned in the Content-Type header.
response - Return the value of the API response. If the value is JSON encoded, this function will decode it and return the value converted to respective types. If the value is form encoded, this function will decode the response and return it as an array. Otherwise, the class will return the value as a string.
This function returns 1 if the call was done successfully.
bool Initialize()
Initialize the class variables and internal state. It must be called before calling other class functions.
Set the server variable before calling this function to let it initialize the class variables to work with the specified server type. Alternatively, you can set other class variables manually to make it work with servers that are not yet built-in supported.
This function returns 1 if it was able to successfully initialize the class for the specified server type.
bool CheckAccessToken(
Check if the access token was retrieved and if it is valid.
Call this function when you need to check of an access token is valid without forcing to redirect the user to the OAuth server authorization page.
If a previously retrieved access token has expired, this function may renew it automatically.
redirect_url - Return the URL of the OAuth server authorization to redirect the user if the access token was not yet retrieved or is not valid.
This function returns 1 if the OAuth protocol was checked without errors.
bool Process()
Process the OAuth protocol interaction with the OAuth server.
Call this function when you need to retrieve the OAuth access token. Check the access_token to determine if the access token was obtained successfully.
This function returns 1 if the OAuth protocol was processed without errors.
bool RevokeToken(
Revoke a previously obtained token so it becomes invalid.
Call this function when you need to invalidate a token that you no longer need to use, so it is not used by any other application.
token_type_hint - Pass the type of token to be revoked if it is not an access token.
This function returns 1 if the OAuth protocol was revoked without errors.
bool Finalize(
Cleanup any resources that may have been used during the OAuth protocol processing or execution of API calls.
Always call this function as the last step after calling the functions Process or CallAPI.
success - Pass the last success state returned by the class or any external code processing the class function results.
This function returns 1 if the function cleaned up any resources successfully.
Output()
Display the results of the OAuth protocol processing.
Only call this function if you are debugging the OAuth authorization process and you need to view what was its results.