我一直在尝试为Docebo构建授权标头,但由于文档描述性不足且其代码示例(仅代码示例)非常混乱,因此我无法使其正常工作。

这基本上是所有Docebo documentation



我正在尝试做的是获取所有用户的列表。

public JsonResult GetCoursesCount()
        {
            const string apiKey = "[API KEY FROM MY DOCEBO PORTAL]";
            const string apiSecret = "[API SECRET FROM MY DOCEBO PORTAL]";
            const string doceboUrl = "[URL OF MY DOCEBO PORTAL]";

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var toEncodeWithSha1 = String.Format("{0},{1}", String.Join(",", new[] {"0", "null"}), apiSecret); // should the values be values or parameters??

                var code = GetSHA1HashData(toEncodeWithSha1);

                var toEncodeWithBase64 = String.Format("{0}:{1}", apiKey, code);

                code = Base64Encode(toEncodeWithBase64);

                var xAuthorisation = String.Format("Docebo {0}", code);

                httpClient.DefaultRequestHeaders.Add("X-Authorization", xAuthorisation);

                var stringContent = JsonConvert.SerializeObject("{ \"from\": \"0\", \"count\": \"null\" }");

                var userResult = httpClient.PostAsync(String.Format("{0}/api/user/listUsers", doceboUrl),
                    new StringContent(stringContent)).Result;

                var userData = JsonConvert.DeserializeObject<dynamic>(userResult.Content.ReadAsStringAsync().Result);

                return new JsonResult { Data = userData, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }

private string GetSHA1HashData(string data)
        {
            //create new instance of md5
            var sha1 = SHA1.Create();

            //convert the input text to array of bytes
            byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(data));

            //create new instance of StringBuilder to save hashed data
            var returnValue = new StringBuilder();

            //loop for each byte and add it to StringBuilder
            foreach (byte @byte in hashData)
            {
                returnValue.Append(@byte.ToString());
            }

            // return hexadecimal string
            return returnValue.ToString();
        }

        private string Base64Encode(string plainText)
        {
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            return Convert.ToBase64String(plainTextBytes);
        }


每当我联系他们的API时,都会收到“ {
  “成功”:错误,
  “ message”:“授权标头值不匹配”,
  “代码”:104
}”。

对此反馈或API文档的易于理解的翻译非常好。

最佳答案

经过长时间的努力(8个小时),我解决了正确的代码。

public JsonResult GetCoursesCount()
        {
            const string apiKey = "[API KEY FROM MY DOCEBO PORTAL]";
            const string apiSecret = "[API SECRET FROM MY DOCEBO PORTAL]";
            const string doceboUrl = "[URL OF MY DOCEBO PORTAL]";

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var listKeyValuePair = new List<KeyValuePair<string,string>>
                {
                    new KeyValuePair<string, string>("from", "0"),
                    new KeyValuePair<string, string>("count", "10")
                };

                var toEncodeWithSha1 = String.Format("{0},{1}", String.Join(",", listKeyValuePair.Select(n => n.Value)), apiSecret); // should the values be values or parameters??

                var code = Sha1Hash(toEncodeWithSha1);

                var toEncodeWithBase64 = String.Format("{0}:{1}", apiKey, code);

                code = Base64Encode(toEncodeWithBase64);

                var xAuthorisation = String.Format("Docebo {0}", code);

                httpClient.DefaultRequestHeaders.Add("X-Authorization", xAuthorisation);

                var content = new FormUrlEncodedContent(listKeyValuePair);

                var userResult = httpClient.PostAsync(String.Format("{0}/api/user/listUsers", doceboUrl),
                    content).Result;

                var responseByteArray = userResult.Content.ReadAsByteArrayAsync().Result;

                var convertedResult = Encoding.UTF8.GetString(responseByteArray, 0, responseByteArray.Length);

                var userData = JsonConvert.DeserializeObject<UserListResult>(convertedResult);

                return new JsonResult { Data = userData, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }

        public class UserListResult
        {
            public List<dynamic> Users { get; set; }
            public bool Success { get; set; }
        }

        private string Sha1Hash(string input)
        {
            return string.Join(string.Empty, SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(input)).Select(x => x.ToString("x2")));
        }

        private string Base64Encode(string plainText)
        {
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            return Convert.ToBase64String(plainTextBytes);
        }


包括PHP示例供参考:

<?php
/**
* DOCEBO, e-learning SAAS
*
* @link http://www.docebo.com/
* @copyright Copyright &copy; 2004-2013 Docebo
*/
class Api {
static public $url = 'yoursite.docebosaas.com';
static public $key = 'your_key_from_api_app';
static public $secret_key = 'your_secret_from_api_app';
static public $sso = 'your_toekn_from_api_app';
static public function getHash($params) {
$res =array('sha1'=>'', 'x_auth'=>'');
$res['sha1']=sha1(implode(',', $params) . ',' . self::$secret_key);
$res['x_auth']=base64_encode(self::$key . ':' . $res['sha1']);
return $res;
}
static private function getDefaultHeader($x_auth) {
return array(
"Host: " . self::$url,
"Content-Type: multipart/form-data",
'X-Authorization: Docebo '.$x_auth,
);
}
static public function call($action, $data_params) {
$curl = curl_init();
$hash_info = self::getHash($data_params);
$http_header =self::getDefaultHeader($hash_info['x_auth']);
$opt = array(
CURLOPT_URL=>self::$url . '/api/' . $action,
CURLOPT_RETURNTRANSFER=>1,
CURLOPT_HTTPHEADER=>$http_header,
CURLOPT_POST=>1,
CURLOPT_POSTFIELDS=>$data_params,
CURLOPT_CONNECTTIMEOUT=>5, // Timeout to 5 seconds
);
curl_setopt_array($curl, $opt);
// $output contains the output string
$output = curl_exec($curl);
// it closes the session
curl_close($curl);
return $output;}
static public function sso($user) {
$time = time();
$token = md5($user.','.$time.','.self::$sso);
return 'http://' . self::$url .
'/doceboLms/index.php?modname=login&op=confirm&login_user=' . strtolower($user) . '&time=' .
$time . '&token=' . $token;
}
}
// sample call
$res = API::call('user/checkUsername', array(
'userid' => 'username_to_chek'
));

关于c# - Docebo-构建授权 header ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27830342/

10-11 03:55