Translate

ebook【Delphi跨平台資料庫程式設計火速上手】電子書出版 (CHT)

Delphi 跨平台資料庫程式設計火速上手,是本關於整合 Delphi 的跨平台技術打造 2-Tier 架構的跨平台 APP 的入門技術書。 全書沒有需要理解的技術知識,只講套路。 力求短時間把製作 APP 的工法熟悉,未來要開發其它的應用程式也能舉一反三。 底下...

2017/08/20

DataSnap REST API Authorization with PHP


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

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:
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:
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)
    {
      request.setRequestHeader("Authorization", "Basic " + this.authentication);
    }
  ...

request.setRequestHeader is key point!

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

PHP code like below:
   $api_url = 'http://localhost:8080/Datasnap/rest/TserverMethods1/EchoString/AAA';

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

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

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

It is finish:


See also:

沒有留言:

張貼留言