如何通过php或html或jquery登录rest api

时间:2015-08-26 06:06:39

标签: php html api rest curl

我想在rest api中使用测试凭据登录...
我发现它可以通过CURL或jQuery等多种方式完成,或者通过下面的代码完成,但我不知道在哪里放或者怎么做

GET /api.php HTTP/1.1
Host: www.example.org
Authorization: Basic QRTYxmYmdLKimmkLKKKQ==

1 个答案:

答案 0 :(得分:2)

AuthBasic(您的授权方法)基于HTTP标头。所以要授权你必须在HTTP请求中发送正确编写的头文件,在你的例子中是:

Authorization: Basic QRTYxmYmdLKimmkLKKKQ==

此字符串是base64编码的字符串:$login:$passwordHere是关于AuthBasic的wiki desc。

这是很多方法。

PHP cURL

您必须设置正确的选项:

$username='ABC';
$password='XYZ';

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

Guzzle

您也可以使用库:

$client = new GuzzleHttp\Client();
$res = $client->get('https://example.com', ['auth' =>  ['user', 'pass']]);

Shell cURL

您在此处设置选项--user

curl --user name:password http://www.example.com

jQuery

对于ajax请求,您必须添加beforeSend方法正确的标头:

beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password)); 
};
相关问题