2016-02-13 194 views
0

我是一名初學者,正在構建一個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); 

回答

1

Laravel是隨狂飲 - 先進的HTTP客戶端庫。使用它可能比低級捲曲更合理。

要做到基本認證與狂飲:

$client = new GuzzleHttp\Client(); 
$response = $client->post('http://example.com/api/conversations', [ 
    'auth' => [ 
     '[email protected]', 
     '1234' 
    ] 
]); 

的響應將是在$響應 - > getBody();

如果您的目標端點使用SSL--在頭中發送證書並不算太壞,但最新的方法是使用臨時令牌(例如API密鑰或OAuth訪問令牌)。

0

除了接受的答案之外,您還可以創建一個通用函數來處理所有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