The Custom authentication code runs each time when the application is going to perform a REST API request. The request description is passed to the code in the request parameter in the form of HttpRequest object. The app expects that the custom code will modify the request and add some authentication information to it.
Parameters passed to the custom authentication code:
connection
RestConnection object. Represents the connection itself. Can be used to run requests against it.
mode
String. Has either "data" or "validate" value. See the OAUTH 2.0 section below
request
HttpRequest object. Description of the request to the REST API the app is about to make. It expects you to add authentication data to it.
code
String. Only used with mode="validation". See the OAUTH 2.0 section below
The process of PHPRunner-created app accessing a REST API can be described by this wokflow:
•Create request object
•Add authentication info to the request object. Here goes the Custom Authentication code
•Send request to the API and receive response
•Parse and process the response
•Show data to the user
In basic cases you only need to add one or two parameters to the request
OAUTH 2.0
When OAUTH 2.0 process with the user logging into the API provider site is used, a multiple step authentication must be performed.
When accessing the API resource for the first time, the app must send the user to the API provider site. Your code should use setAuthorizationRequest function to signal about it.
// create authorization request
$authRequest = new HttpRequest( $authUrl );
...
// send authorization request to the application
$connection->setAuthorizationRequest( $authRequest );
// don't do anything else
return true;
After the user logs in on the API provider's site, the API sends back authorization code to the application. The application must validate the code and receive the access token
When using custom authentication, the custom code is called with mode parameter set to "validation" and code parameter has the code to validate.
if( $mode == "validate" ) {
// create validation request
$validateRequest = new HttpRequest( $tokenUrl, "POST" );
...
// run validation request and parse result
$oauthToken = $connection->requestOauthToken( $validateRequest );
// save access token
$connection->setOauthToken( $oauthToken );
// don't do anything else for now
return true;
}
After successful validation the code should save the received access token. When called next time, the code should retrieve the saved access token and add it to the request.
$oauthToken = $connection->getOauthToken();
$request->headers["Authorization"] = "Bearer " . $oauthToken["access_token"];