我是一名初学者,负责构建rest api和身份验证。 我刚刚阅读了以下内容并解释了一个非常简单的设置:
laravel 5 rest api basic authentication
在文章底部,文章解释了不要使用标题或网址发送用户名和密码。
我的问题基本上是:任何人都可以举例说明如何使用上面的例子中的cUrl请求吗?
例如:
$service_url = 'http://example.com/api/conversations';
$curl = curl_init($service_url);
$curl_post_data = array(
'user' => 'user@user.com',
'passw' => '1234'
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
curl_close($curl);
答案 0 :(得分:1)
Laravel附带了Guzzle--一个高级HTTP客户端库。使用它比使用低级cURL更合理。
使用Guzzle进行基本身份验证:
$client = new GuzzleHttp\Client();
$response = $client->post('http://example.com/api/conversations', [
'auth' => [
'user@user.com',
'1234'
]
]);
响应将在$ response-> getBody();
中如果您的目标端点使用SSL - 在标头中发送凭据并不是太糟糕,但时髦的方法是使用临时令牌(例如API密钥或OAuth访问令牌)。
答案 1 :(得分:0)
除了接受的答案,您还可以创建一个通用函数来处理所有卷曲请求。
您可以使用以下函数调用外部Web服务并返回数据/身份验证信息。
/*=============================================
* Call External Webservices using CURL
*
* @param $requestURL, $header -> (OPTIONAL)
* @return json
#=============================================*/
public function curlRequest($requestURL, $headers = array())
{
$getData = curl_init($requestURL);
curl_setopt($getData, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($getData, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($getData, CURLOPT_SSL_VERIFYHOST, false);
if (count($headers) != 0) {
curl_setopt($getData, CURLOPT_HTTPHEADER, $headers);
}
$response = curl_exec($getData);
return json_decode($response);
}
使用特定于案例的示例来使用上述功能进行身份验证:
$requestURL = 'http://www.example.com/api/userLogin';
$userAuthInfo = [
'email'=> 'example@example.com',
'password'=>'123456'
];
$result = $this->curlRequest($requestURL, $userAuthInfo);
dd($result); //Print the Result of the Authentication request