2017/08/20

DataSnap REST API Authorization with PHP


About Authentication with DataSet REST JavaScript client.
In connection.js:

1
2
3
4
5
function setCredentials(user, password)
{
   connectionInfo.authentication = convertStringToBase64(user + ":" + password);
   var testCreds = new DSAdmin(connectionInfo).GetPlatformName();
}

connectionInfo.authentication will send user and password to DataSnap DSAuthenticationManager.OnUserAuthenticate.

Well, how to send it?


In serverfunctions.js:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function DSAdmin(connectionInfo)
{
  /*
   * @return result - Type on server: string
   */
  this.GetPlatformName = function() {
    var returnObject = this.executor.executeMethod('GetPlatformName', "GET", [], arguments[0], true, arguments[1], arguments[2]);
    if (arguments[0] == null) {
      if (returnObject != null && returnObject.result != null && isArray(returnObject.result)) {
        var resultArray = returnObject.result;
        var resultObject = new Object();
        resultObject.result = resultArray[0];
        return resultObject;
      }
      return returnObject;
    }
  };

DSAdmin object use "executor.executeMethod" include "connectionInfo" send request to DSServer.

In ServerFunctionExecutor:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function ServerFunctionExecutor(className, connectionInfo, owner)
{
  this.executeMethod = function(methodName, requestType, params, callback, hasResult, requestFilters, accept) {
    var url = this.getMethodURL(methodName, requestType, params, requestFilters);    
    return this.executeMethodURL(url[0], url[1], requestType, callback, hasResult, accept);
  };
  ...
  this.executeMethodURL = function(url, contentParam, requestType, callback, hasResult, accept) {
  ...
    if (this.authentication != null)
    {
      <span style="color: red;">request.setRequestHeader("Authorization", "Basic " + this.authentication);</span>
    }
  ...

request.setRequestHeader is key point!

Hence, if we want call DataSnap REST API in PHP, us need to use Authorization.

PHP code like below:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
   $api_url = 'http://localhost:8080/Datasnap/rest/TserverMethods1/EchoString/AAA';

   $client_id = 'myclientid';
   $client_secret = 'myclientsecret';

   $context = stream_context_create(array(
     'http' =&gt; array(
       'header' =&gt; "Authorization: Basic " . base64_encode("$client_id:$client_secret"),
     ),
   ));

  $result = file_get_contents($api_url, false, $context);
  echo $result;

It is finish:


See also:

沒有留言:

張貼留言