Laravel rest api身份验证
问题描述:
我是一名初学者,正在构建一个rest api和身份验证。 我刚刚阅读下面的,并解释非常简单的设置:Laravel rest api身份验证
laravel 5 rest api basic authentication
在文章解释不与标题或URL中的用户名发送和密码底部。
我的问题是基本的:任何人都可以给我一个例子如何使用上面的例子的cUrl请求?
例如:
$service_url = 'http://example.com/api/conversations';
$curl = curl_init($service_url);
$curl_post_data = array(
'user' => '[email protected]',
'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);
答
Laravel是随狂饮 - 先进的HTTP客户端库。使用它可能比低级卷曲更合理。
要做到基本认证与狂饮:
$client = new GuzzleHttp\Client();
$response = $client->post('http://example.com/api/conversations', [
'auth' => [
'[email protected]',
'1234'
]
]);
的响应将是在$响应 - > getBody();
如果您的目标端点使用SSL--在头中发送证书并不算太坏,但最新的方法是使用临时令牌(例如API密钥或OAuth访问令牌)。
答
除了接受的答案之外,您还可以创建一个通用函数来处理所有curl请求。
您可以使用以下函数调用外部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'=> '[email protected]',
'password'=>'123456'
];
$result = $this->curlRequest($requestURL, $userAuthInfo);
dd($result); //Print the Result of the Authentication request