AbstractOAuthClient
abstract class AbstractOAuthClient implements OAuthClientInterface
Base class for all Oauth clients :
Implement the OAuth protocol to retrieve a token from a server to authorize the access to an API on behalf of the current user.
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, 2.0 and OpenID. It abstracts the differences between these protocol versions, so the class usage is the same independently of the OAuth version of the server.
The OAuthBuiltinProviders class provides built-in support to several popular OAuth providers, so you do not have to manually configure all the details to access those providers.
If you need to access one provider that is not yet directly supported by the OAuthBuiltinProviders class, you need to configure it explicitly setting the variables:
- protocol
- version
- parameters_in_url
- authorization_in_header
- request_token_endpoint
- authorization_endpoint
- reauthentication_parameter
- pin_dialog_url
- offline_access_parameter
- append_state_to_redirect_uri
- token_endpoint
- scope
- username
- password
- grant_type and
- token_endpoint
Before proceeding to the actual OAuth authorization process, you need to have registered your application with the OAuth provider. 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 variable redirect_uri before calling the authenticate function to make the class perform the necessary interactions with the OAuth provider.
The OAuth protocol involves multiple steps that include redirection to the OAuth provider. 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, 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:
- accessToken,
- accessTokenSecret,
- accessTokenExpiry,
- accessTokenType.
You may want to store these values to use them later when calling the server APIs. 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.
Properties
protected string | $oauthUserAgent | The User-Agent used in HTTP requests | |
protected bool | $debug | Control whether debug output is enabled | |
protected bool | $debugHttp | Control whether the dialog with the remote Web server should also be logged. | |
protected string | $logFileName | Name of the file to store log messages | |
protected bool | $exit | Determine if the current script should be exited. | |
protected string | $debugOutput | Capture the debug output generated by the class | |
protected string | $debugPrefix | Mark the lines of the debug output to identify actions performed by this class. | |
protected string | $accessToken | Access token obtained from the OAuth provider | |
protected string | $accessTokenSecret | Access token secret obtained from the OAuth provider | |
protected string | $accessTokenExpiry | Timestamp of the expiry of the access token obtained from the OAuth provider. | |
protected string | $accessTokenType | Type of access token obtained from the OAuth provider. | |
protected array | $accessTokenResponse | The original response for the access token request | |
protected string | $refreshToken | Refresh token obtained from the OAuth provider | |
protected object | $idToken | The id_token value from OAuth providers compatible with OpenID Connect. | |
protected integer | $responseStatus | HTTP response status returned by the server when calling an API | |
protected array | $responseHeaders | HTTP response headers returned by the server when calling an API | |
protected string | $responseBody | HTTP response body returned by the server when calling an API | |
protected integer | $responseTime | Time of response of the HTTP request | |
protected OAuthClientStrategy | $strategy | OAuth Client Strategy object | |
protected OAuthProvider | $provider | OAuth Provider object | |
protected TokenStorageInterface | $storage | Token Storage object |
Methods
Constructs an OAuth client object for the given provider name
Determines whether debug output is enabled or not
Determines whether the dialog with the remote Web server should also be logged or not.
Determine if the current script should be exited.
Returns the obtained access token upon successful OAuth authentication.
Returns the access token secret obtained from the OAuth provider.
Returns the timestamp of the expiry of the access token obtained from the OAuth provider.
Returns the type of access token obtained from the OAuth provider.
Returns the original response for the access token request
Returns the obtained refresh token upon successful OAuth authentication.
Returns the obtained ID token upon successful OpenID authentication.
Returns the HTTP response status returned by the server when calling an API.
Returns the HTTP response headers returned by the server when calling an API.
Returns the HTTP response header value returned by the server when calling an API for a given header name.
Returns the HTTP response body returned by the server when calling an API.
Returns the User-Agent used in HTTP requests.
Returns the time of the response of the HTTP request.
Returns the current instance of the OAuthProvider class.
Returns the current instance of the OAuthClientStrategy class.
Enables or disables the debug mode.
Enables or disables logging of the dialog with the remote Web server.
Sets the name of the file to store log messages.
Determines if the current script should be exited.
Sets the URL of the current script page that is calling this class.
Sets the identifier of your application registered with the OAuth provider.
Sets the secret value assigned to your application.
Sets access token obtained from the OAuth provider
Sets the access token secret obtained from the OAuth 1.0 or 1.0a provider
Sets the timestamp of the expiry of the access token obtained from the OAuth provider.
Sets the type of access token obtained from the OAuth provider.
Sets the original response for the access token request.
Sets the refresh token obtained from the OAuth provider.
Sets the id_token object from OAuth providers compatible with OpenID Connect.
Sets the HTTP response status returned by the server when calling an API.
Sets the HTTP response headers returned by the server when calling an API.
Sets the HTTP response body returned by the server when calling an API.
Changes the User-Agent used in HTTP requests.
Sets the time of the response of the HTTP request.
Writes a message to the log output if debugging is enabled.
Replaces the placeholders in the URL of the authorization endpoint and returns it.
Replaces the placeholders in the URL of the token endpoint and returns it.
Replaces the placeholders in the URL of the revocation endpoint and returns it.
Returns the value of the state parameter returned by the OAuth provider.
Returns the value of the code returned by the authorization endpoint of the OAuth provider.
Returns the error returned by the OAuth provider.
Returns the denied access token returned by the OAuth provider, if any.
Returns the request token received from the OAuth 1.0(a) provider
Returns the verification code received from the OAuth 1.0(a) provider
Redirect the user browser to a given page.
Sign the request data in PLAINTEXT, HMAC_SHA1 or RSA_SHA1 using a key composed from the secret client registered with the provider and the oauth token secret returned by the token request endpoint.
Sends a HTTP request to the OAuth provider.
Composes a OAuth request to be sent to the OAuth provider.
Sends a OAuth request to the OAuth provider.
Converts the response body of an OAuth request based on the options in the provided argument.
Checks if there is a stored access token
Checks if the stored access token is valid
Send a HTTP request to the Web services API using a previously obtained access token via OAuth.
Returns the information about the resource owner using a previously obtained access token via OAuth.
Returns the information about the resource owner.
Checks the access token state before calling an API.
Initialize the class variables and internal state. It must be called before calling other class functions.
Merges two arrays recursively.
Initializes the options registered with the OAuth provider.
Sends a OAuth request to the discovery endpoint of the OpenID provider in order to obtain the configuration information, which is the list of all endpoints and the list of supported OAuth elements.
Checks that the authenticate method has not already been called
Checks if the user is authenticated with the current OAuth provider.
Process the OAuth protocol interaction with the OAuth provider.
Check if the access token was retrieved and if it is valid.
Reset the access token to a state back when the user has not yet authorized the access to the OAuth provider API.
Determines whether the revokeToken function can be called.
Revoke a previously obtained token so it becomes invalid.
Cleanup any resources that may have been used during the OAuth protocol processing or execution of API calls.
Determines whether the logOut function can be called.
Calls the end-session endpoint to notify the provider that the end-user has logged out of the relying party site.
Details
at line 276
__construct(string $provider = "")
Constructs an OAuth client object for the given provider name
at line 286
protected bool
isDebug()
Determines whether debug output is enabled or not
at line 296
protected bool
isDebugHttp()
Determines whether the dialog with the remote Web server should also be logged or not.
at line 303
bool
shouldExit()
Determine if the current script should be exited.
Call this function after calling the authenticate function and exit your script immediately if this function returns true.
at line 310
string
getAccessToken()
Returns the obtained access token upon successful OAuth authentication.
Call this function to get the obtained access token upon successful OAuth authorization.
at line 323
protected string
getAccessTokenSecret()
Returns the access token secret obtained from the OAuth provider.
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.
at line 337
protected string
getAccessTokenExpiry()
Returns the timestamp of the expiry of the access token obtained from the OAuth provider.
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.
at line 349
protected string
getAccessTokenType()
Returns the type of access token obtained from the OAuth provider.
Check this variable to get the obtained access token type upon successful OAuth authorization.
at line 361
protected array
getAccessTokenResponse()
Returns the original response for the access token request
Check this variable if the OAuth provider returns custom parameters in the request to obtain the access token.
at line 368
string
getRefreshToken()
Returns the obtained refresh token upon successful OAuth authentication.
Call this function to get the obtained refresh token upon successful OAuth authorization.
at line 375
IdToken
getIdToken()
Returns the obtained ID token upon successful OpenID authentication.
Call this function if the OAuth provider returns id_token values.
at line 389
protected integer
getResponseStatus()
Returns the 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.
at line 402
protected array
getResponseHeaders()
Returns the 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.
at line 414
protected string|array|null
getResponseHeader(string $header)
Returns the HTTP response header value returned by the server when calling an API for a given header name.
at line 434
protected string
getResponseBody()
Returns the HTTP response body 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.
at line 443
protected string
getOauthUserAgent()
Returns the User-Agent used in HTTP requests.
at line 452
protected integer
getResponseTime()
Returns the time of the response of the HTTP request.
at line 459
OAuthProvider
getProvider()
Returns the current instance of the OAuthProvider class.
at line 466
OAuthClientStrategy
getStrategy()
Returns the current instance of the OAuthClientStrategy class.
at line 482
AbstractOAuthClient
setDebug(bool $debug)
Enables or disables the debug mode.
Set this variable to true if you need to check what is going on during calls to the class. When enabled, the debug output goes either to the variable debugOutput and the PHP error log.
at line 497
AbstractOAuthClient
setDebugHttp(bool $debugHttp)
Enables or disables logging of the dialog with the remote Web server.
Set this variable to true if you want to inspect the data exchange with the OAuth provider.
at line 513
AbstractOAuthClient
setLogFileName(string $logFileName)
Sets the 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 true.
at line 525
protected AbstractOAuthClient
setExit(bool $exit)
Determines if the current script should be exited.
at line 537
AbstractOAuthClient
setRedirectUri(string $redirect_uri)
Sets the URL of the current script page that is calling this class.
at line 549
AbstractOAuthClient
setClientId(string $client_id)
Sets the identifier of your application registered with the OAuth provider.
at line 561
AbstractOAuthClient
setClientSecret(string $client_secret)
Sets the secret value assigned to your application.
at line 573
protected AbstractOAuthClient
setAccessToken(string $accessToken)
Sets access token obtained from the OAuth provider
at line 585
protected AbstractOAuthClient
setAccessTokenSecret(string $accessTokenSecret)
Sets the access token secret obtained from the OAuth 1.0 or 1.0a provider
at line 598
protected AbstractOAuthClient
setAccessTokenExpiry(string $accessTokenExpiry)
Sets the timestamp of the expiry of the access token obtained from the OAuth provider.
at line 610
protected AbstractOAuthClient
setAccessTokenType(string $accessTokenType)
Sets the type of access token obtained from the OAuth provider.
at line 622
protected AbstractOAuthClient
setAccessTokenResponse(array $accessTokenResponse)
Sets the original response for the access token request.
at line 634
protected AbstractOAuthClient
setRefreshToken(string $refreshToken)
Sets the refresh token obtained from the OAuth provider.
at line 646
protected AbstractOAuthClient
setIdToken(IdToken|null $idToken)
Sets the id_token object from OAuth providers compatible with OpenID Connect.
at line 658
protected AbstractOAuthClient
setResponseStatus(integer $responseStatus)
Sets the HTTP response status returned by the server when calling an API.
at line 670
protected AbstractOAuthClient
setResponseHeaders(array $responseHeaders)
Sets the HTTP response headers returned by the server when calling an API.
at line 682
protected AbstractOAuthClient
setResponseBody(string $responseBody)
Sets the HTTP response body returned by the server when calling an API.
at line 694
protected AbstractOAuthClient
setOauthUserAgent(string $oauthUserAgent)
Changes the User-Agent used in HTTP requests.
at line 706
protected AbstractOAuthClient
setResponseTime(integer $responseTime)
Sets the time of the response of the HTTP request.
at line 718
bool
trace(string $message)
Writes a message to the log output if debugging is enabled.
at line 740
protected string
getAuthorizationEndpoint(string $redirectUri = '', string $state = '', string $nonce = '')
Replaces the placeholders in the URL of the authorization endpoint and returns it.
at line 773
protected string
getTokenEndpoint()
Replaces the placeholders in the URL of the token endpoint and returns it.
at line 784
protected string
getRevocationEndpoint(string $token)
Replaces the placeholders in the URL of the revocation endpoint and returns it.
at line 797
protected string|false|null
getRequestState()
Returns the value of the state parameter returned by the OAuth provider.
at line 812
protected string|false|null
getRequestCode()
Returns the value of the code returned by the authorization endpoint of the OAuth provider.
at line 821
protected string|null
getRequestError()
Returns the error returned by the OAuth provider.
at line 830
protected string|null
getRequestDenied()
Returns the denied access token returned by the OAuth provider, if any.
at line 839
protected string|null
getRequestToken()
Returns the request token received from the OAuth 1.0(a) provider
at line 848
protected string|null
getRequestVerifier()
Returns the verification code received from the OAuth 1.0(a) provider
at line 864
protected
redirect(string $url)
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.
at line 887
protected array
signRequestData(string $url, string $method, array $parameters, array $oauth, string $requestContentType, bool $hasFiles, bool $postDataInUri)
Sign the request data in PLAINTEXT, HMAC_SHA1 or RSA_SHA1 using a key composed from the secret client registered with the provider and the oauth token secret returned by the token request endpoint.
For OAuth 1.0 an Oauth 1.0a only.
at line 905
protected
sendHttpRequest(OAuthRequest $oauthRequest, array $options = [])
Sends a HTTP request to the OAuth provider.
at line 983
protected OAuthRequest|false
prepareOAuthRequest(string $url, string $method, array $parameters, array $options, array $oauth = null)
Composes a OAuth request to be sent to the OAuth provider.
at line 1102
protected string|object|array|SimpleXMLElement|false
sendOAuthRequest(string $url, string $method, array $parameters, array $options, array $oauth = null)
Sends a OAuth request to the OAuth provider.
at line 1149
protected string|object|array|SimpleXMLElement|false
convertResponseBody(array $options)
Converts the response body of an OAuth request based on the options in the provided argument.
at line 1207
protected bool
isThereAStoredAccessToken()
Checks if there is a stored access token
at line 1216
protected bool
isStoredAccessTokenValid()
Checks if the stored access token is valid
at line 1278
abstract mixed
callAPI(string $url, string $method, array $parameters, array $options)
Send a HTTP request to the Web services API using a previously obtained access 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 authenticate 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 responseHeaders variable returns the HTTP response headers. The responseBody variable returns the HTTP response body.
at line 1283
ResourceOwner
getResourceOwner(string $endpoint = null)
Returns the information about the resource owner using a previously obtained access token via OAuth.
This function must be called after having previously obtained an access token through the OAuth protocol using the authenticate 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.
at line 1308
ResourceOwner
fetchResourceOwner(array $options)
Returns the information about the resource owner.
This function is a high-level function that perform all the necessary actions (initalization, authentication, ...) before requesting the information about the resource owner.
at line 1329
protected bool
checkTokenBeforeCall($options)
Checks the access token state before calling an API.
at line 1346
bool
initialize(array $options = [])
Initialize the class variables and internal state. It must be called before calling other class functions.
Set the provider variable before calling this function to let it initialize the class variables to work with the specified provider. Alternatively, you can set other class variables manually to make it work with providers that are not yet built-in supported.
at line 1406
private array
deepMerge(array $arr1, array $arr2)
Merges two arrays recursively.
array_merge_recursive does indeed merge arrays, but it converts values with duplicate keys to arrays rather than overwriting the value in the first array with the duplicate value in the second array, as array_merge does. I.e., with array_merge_recursive, this happens
at line 1423
protected void
initializeRegitrationOptions($options)
Initializes the options registered with the OAuth provider.
at line 1465
protected
discover(string $discoveryEndpoint)
Sends a OAuth request to the discovery endpoint of the OpenID provider in order to obtain the configuration information, which is the list of all endpoints and the list of supported OAuth elements.
at line 1480
protected
checkNoToken()
Checks that the authenticate method has not already been called
at line 1490
bool
isAuthenticated()
Checks if the user is authenticated with the current OAuth provider.
Call this function if you want to know if the user needs to log in to access the resources he owns without doing so.
at line 1507
bool
authenticate()
Process the OAuth protocol interaction with the OAuth provider.
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.
at line 1522
abstract string|bool
checkAccessToken(string $redirectUrl)
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 provider authorization page.
If a previously retrieved access token has expired, this function may renew it automatically.
at line 1527
bool
resetAccessToken()
Reset the access token to a state back when the user has not yet authorized the access to the OAuth provider 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.
at line 1534
bool
canRevokeToken()
Determines whether the revokeToken function can be called.
at line 1552
bool
revokeToken(string $tokenTypeHint = 'access_token')
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.
at line 1595
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 authenticate() or callAPI(...).
at line 1601
bool
canLogOut()
Determines whether the logOut function can be called.
at line 1615
logOut(string $redirect = null)
Calls the end-session endpoint to notify the provider that the end-user has logged out of the relying party site.